0

我正在尝试复制一个文本文件,但是当代码完成执行时,我只有文件中的最后一行文本。显然,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());
4

1 回答 1

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");
  }
}
于 2013-03-12T19:06:19.087 回答