Java 使用 Commons IO 写入文件中的新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19361633/
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
Writing to a new line in a file using Commons IO?
提问by user2879044
I know that
我知道
FileUtils.writeStringToFile(myfile.txt, "my string", true);
adds 'my string' to the end of myfile.txt, so it looks like
将“我的字符串”添加到 myfile.txt 的末尾,所以它看起来像
previous stringsmy string
But is there any way to use Commons IO to write a string to a new line in a file, to change the file to
但是有什么方法可以使用Commons IO将字符串写入文件中的新行,将文件更改为
previous strings
my string
采纳答案by user987339
Java use \n
to mark new line so try with:
Java 用于\n
标记新行,因此请尝试:
FileUtils.writeStringToFile(myfile.txt, "\nmy string", true);
回答by Maxim Shoustin
In addition to above mentioned response;
除了上述响应;
If you doesn't have huge file you can write:
如果你没有大文件,你可以写:
List<String> lines = Files.readAllLines(Paths.get(myfile.txt), StandardCharsets.UTF_8);
lines.add("my string");
Files.write(Paths.get(myfile.txt), lines, StandardCharsets.UTF_8);
Generally its good to add new row in the middle of file
通常最好在文件中间添加新行
List<String> lines = Files.readAllLines(Paths.get(myfile.txt)), StandardCharsets.UTF_8);
lines.add(6, "my string"); // for example
Files.write(Paths.get(myfile.txt), lines, StandardCharsets.UTF_8);
回答by SanSolo
declare
宣布
final String newLine = System.getProperty("line.separator");
and in call, FileUtils.writeStringToFile(myfile.txt, yourVariable+newLine, true);
在通话中, FileUtils.writeStringToFile(myfile.txt, yourVariable+newLine, true);
i use a variable , so this was more useful for me
我使用一个变量,所以这对我更有用