具有附加模式的 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
Java FileWriter with append mode
提问by Progress Programmer
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?
我目前正在使用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 true
as a second argument to FileWriter
to turn on "append" mode.
通过true
为第二个参数FileWriter
打开“追加”模式。
fout = new FileWriter("filename.txt", true);
回答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 true
as 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.
希望这能解决您的问题。