2013-03-12 84 views
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()); 

回答

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"); 
    } 
} 
+0

但随后它不能看到bufferreader出来,但filewritter和bufferreader必须在尝试捕捉因此与范围我必须在同一块out.write还是有anotherway希望得到帮助 – user2155009 2013-03-12 20:45:36

相关问题