将源文件复制到目标文件,同时输出源文件内容,需要提供一个源文件和目标文件路径参数(如果不存在则自动创建)
public static void copyTxt(String sourceFile, String targetFile){ try{ String encoding = "GBK"; File file = new File(sourceFile); if(file.exists() && file.isFile()){ //判断文件是否存在 FileInputStream input = new FileInputStream(file); //字节流 FileOutputStream output = new FileOutputStream(new File(targetFile)); InputStreamReader read = new InputStreamReader (input,encoding);//字符流 OutputStreamWriter write = new OutputStreamWriter(output,encoding); BufferedReader bufferedReader = new BufferedReader (read);//缓冲流 BufferedWriter bufferedWriter = new BufferedWriter(write); String line = ""; while ( (line = bufferedReader.readLine() )!= null ){ System.out.println(line); bufferedWriter.write(line + "\n"); } bufferedReader.close(); bufferedWriter.close(); }else { System.out.println("找不到指定的文件"); } }catch(IOException e){ System.out.println("读取文件内容出错"); e.printStackTrace(); } } }
时间: 2024-10-09 05:09:14