java 使用FileReader 和 FileWriter 操作文件

时间:2022-08-04 21:39:14

1   使用FileReader  和 FileWriter  操作文件

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
 * FileReader  和Filewriter   读写文本
 */
public class FileReaderWriter {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   //FileReader  很方便操作纯文本文件
   FileReader filereader = new FileReader("1.txt");
      BufferedReader bufferedReader = new BufferedReader(filereader);
     
      FileWriter fileWriter = new FileWriter("1_new.txt");
      BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
      String line;
      while((line =bufferedReader.readLine())!=null )
      {
       bufferedWriter.write(line+"\n");
      }
      bufferedWriter.flush();//所有带有缓冲的 都要强制全部输出
      bufferedWriter.close();
      fileWriter.close();
      bufferedReader.close();
      filereader.close();
      System.out.println("done");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


案例 结果:

done