Java FileWriter with append mode

拟墨画扇 提交于 2019-12-16 22:52:47

问题


I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?

   fout = new FileWriter(
    "Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
    fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
    fileout.close();

回答1:


Pass true as a second argument to FileWriter to turn on "append" mode.

fout = new FileWriter("filename.txt", true);

FileWriter usage reference




回答2:


From the Javadoc, you can use the constructor to specify whether you want to append or not.

public FileWriter(File file, boolean append) throws IOException

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.




回答3:


You can open the FileWriter in append mode by passing true as the second parameter:

fout = new FileWriter("Distribution_" + ... + ".txt", true);



回答4:


You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.

For example,

fout = new FileWriter( "Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);

Hope this would solve your problem.



来源:https://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!