java java用新行写入文件末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10609775/
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 write to the end of file with new line
提问by LinCR
I want to write results to the end of the file using java
我想使用 java 将结果写入文件的末尾
FileWriter fStream;
try {
fStream = new FileWriter("recallPresision.txt", true);
fStream.append("queryID=" + queryID + " " + "recall=" + recall + " Pres=" + presision);
fStream.append("\n");
fStream.flush();
fStream.close();
} catch (IOException ex) {
Logger.getLogger(query.class.getName()).log(Level.SEVERE, null, ex);
}
I put "\n"
in the statement , it writes to the file but not with new line
我放入"\n"
语句,它写入文件但不使用新行
I want to print results with new line
我想用新行打印结果
回答by Jeffrey
The newline sequence is system dependent. On some systems its \n
, on others it's \n\r
, \r\n
, \r
or something else entirely different. Luckily, Java has a built in property which allows you to access it:
换行序列取决于系统。在某些系统上它的\n
,别人是\n\r
,\r\n
,\r
或别的东西完全不同。幸运的是,Java 有一个内置属性,允许您访问它:
String newline = System.getProperty("line.separator");
回答by Andrew Thompson
Wrong
错误的
fStream.append("\n");
Right
对
// don't guess the line separator!
fStream.append(System.getProperty("line.separator"));
回答by Paul Vargas
You could also change to:
您还可以更改为:
fStream = new FileWriter("recallPresision.txt", true);
PrintWriter out = new PrintWriter(fStream);
out.println("queryID=" + queryID + " " + "recall=" + recall + " Pres=" + presision);
out.flush();
out.close();
fStream.close();
回答by Kevin
It does print the newline, what you want is a blank line at the end. Add another \n
.
它确实打印了换行符,你想要的是最后一个空行。添加另一个\n
.
回答by Kevin
Try using \r\n
instead.
尝试使用\r\n
。
Also, you should find that if you open your text file in a rich-text-editor, such as wordpad, your append has actually worked.
此外,您应该会发现,如果您在富文本编辑器(例如写字板)中打开文本文件,您的附加内容实际上已经起作用了。
Edit: Ignore me. Jeffery and Andrew's answers are much better.
编辑:无视我。杰弗里和安德鲁的答案要好得多。