java Files.write() :在文本文件中追加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41789470/
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-11-03 06:09:34  来源:igfitidea点击:

Files.write() : appending new lines in a text file

javajava-8

提问by FSm

I'm using the code below to write into a text file

我正在使用下面的代码写入文本文件

String content = "I Love Java";
Files.write(Paths.get(gg), (content + "\n").getBytes(UTF_8),StandardOpenOption.CREATE,StandardOpenOption.APPEND);

After 3 times of run, the text is saved into the the text as :

运行3次后,文本保存到文本中为:

I Love JavaI Love JavaI Love Java

But, I want the text in the text file looks like:

但是,我希望文本文件中的文本如下所示:

I Love Java 
I Love Java
I Love Java

Any help please ?

请问有什么帮助吗?

回答by davidxxx

You should avoid specific new line separators such as "\n"or "\r\n"that depends on the OS and favor the use of the System.lineSeparator()constant that applies at runtime the separator of the OS on which the JVM runs.

您应该避免使用特定的新行分隔符,例如取决于操作系统的"\n""\r\n",并倾向于使用System.lineSeparator()在运行时适用于运行 JVM 的操作系统的分隔符的常量。