Java N / IO中的行分隔符? [英] Line separator in Java N/IO?
本文介绍了Java N / IO中的行分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 java.nio.file
写入txt文件时插入新行?
以下代码生成一个txt文件,其中一行 ABCDEF
,而不是两行 ABC
和 DEF
:
How do I insert new line when writing to a txt file using java.nio.file
?
The following code produces a txt file with one line ABCDEF
, instead of two separate lines ABC
and DEF
:
public static void main(String args[]) throws IOException {
final Path PATH = Paths.get("test.txt");
String test = "ABC\nDEF";
Files.write(PATH, test.getBytes());
}
推荐答案
从Java 7开始,你应该使用 系统.lineSeparator()
而不是硬编码 \ n
,因为行分隔符实际上取决于代码将运行的机器。
Beginning with Java 7, you should use System.lineSeparator()
instead of hard coding \n
, since the line separator really depends on which machine the code will run.
public static void main(String args[]) throws IOException {
final Path PATH = Paths.get("test.txt");
String test = "ABC" + System.lineSeparator() + "DEF";
Files.write(PATH, test.getBytes());
}
如果你还在使用Java 6或更早版本,那么 System.getProperty(line.separator)
(参见Oracle文档)。
If you are still using Java 6 or older, the same is achieved with System.getProperty("line.separator")
(see Oracle docs).
这篇关于Java N / IO中的行分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文