写入文件但只保存最后一行

时间:2013-03-12 19:02:04

标签: java file io

我正在尝试复制文本文件,但是当代码完成执行时,我只有文件中的最后一行文本。显然scanLine()会覆盖相同的行,但我无法解决这个问题。有什么想法吗?

do{                 
  try{ 
    FileWriter name = new FileWriter("/home/fok/Desktop/out");
    BufferedWriter out = new BufferedWriter(name);
    a=x.nextLine();scanner x grabs next line and sets it string a
    out.write(a);//writes a to file
    out.close();//closees file
  } catch (IOException ioe){
    System.out.println("file writer error");
  } 

} while(x.hasNext());

1 个答案:

答案 0 :(得分:1)

很简单,你正在关闭并打开for循环中的文件。

 public void readfile(){
   try {           
     FileWriter name = new FileWriter("/home/fok/Desktop/out");
     BufferedWriter out = new BufferedWriter(name);
      do {                 
        a=x.nextLine();scanner x grabs next line and sets it string a
        out.write(a);//writes a to file
      } while(x.hasNext());
      out.close();//closees file
   } catch (IOException ioe){
      System.out.println("file writer error");
  }
}