具有附加模式的 Java FileWriter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1225146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:07:38  来源:igfitidea点击:

Java FileWriter with append mode

javafilewriter

提问by Progress Programmer

I'm currently using FileWriterto 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?

我目前正在使用FileWriter创建和写入文件。有什么方法可以每次写入同一个文件而不删除其中的内容?

   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();

采纳答案by Amber

Pass trueas a second argument to FileWriterto turn on "append" mode.

通过true为第二个参数FileWriter打开“追加”模式。

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

FileWriter usage reference

FileWriter 使用参考

回答by Peter

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

Javadoc,您可以使用构造函数来指定是否要附加。

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.

public FileWriter(File file, boolean append) 抛出 IOException

给定一个 File 对象构造一个 FileWriter 对象。如果第二个参数为真,则字节将写入文件的末尾而不是开头。

回答by Matthew Crumley

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

您可以通过true作为第二个参数传递以追加模式打开 FileWriter :

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

回答by jatanp

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.

您可以将 true 作为第二个参数传递给 FileWriter 的构造函数,以指示编写器附加数据而不是重写文件。

For example,

例如,

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

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

Hope this would solve your problem.

希望这能解决您的问题。