Java Formatter not allowing new line character?

人走茶凉 提交于 2019-12-24 11:01:08

问题


So, I've got the following code to write to a file:

Formatter output = ....... // Creating the formatter works, writes to appropriate file.

output.format("%d\n", records.length);
for(GradeRecord gR:records)
{
    output.format(gR.toString() + "\n");
}

Only problem is, the output doesn't have newline characters.

Doesn't work if I replace "\n" with "\r", either.

...I don't know why this doesn't work. Output is created and writes correctly. (I see the file created and everything is written in it, except for newline characters.)


回答1:


you can use the format "%n" to output the platform specific newline using a formatter.




回答2:


You want to use the correct line break string regardless of what platform it's being run on. You can do this dynamically using

String newline = System.getProperty("line.separator");

So you can later do

output.format(gR.toString() + newline);




回答3:


You can try using \\n instead of \n



来源:https://stackoverflow.com/questions/5494581/java-formatter-not-allowing-new-line-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!