java “\n”分隔符问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5649362/
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
"\n" delimiters issue
提问by user694485
I have a stringbuilder object, that a line of data gets added to.
我有一个 stringbuilder 对象,其中添加了一行数据。
after each line gets added, I append a "\n" on the end to indicate a new line.
添加每一行后,我在末尾附加一个“\n”以指示新行。
this stringbuilder object, finalised, gets written to a flat file.
这个 stringbuilder 对象,最终确定,被写入一个平面文件。
When I open the flat file in notepad I get a small rectangle after every line and the column formatting is ruined.
当我在记事本中打开平面文件时,每行后都会出现一个小矩形,并且列格式被破坏了。
When I open the flat file in wordpad, the new line is taken into consideration and the column formatting is perfect.
当我在写字板中打开平面文件时,会考虑新行并且列格式很完美。
I have tried all ways I know of removing the new line entry before it gets written, but this removes the formatting when written to the flat file. I need the new line for the formatting of the columns.
我已经尝试了所有我知道的在写入之前删除新行条目的方法,但这会在写入平面文件时删除格式。我需要用于列格式的新行。
how can I output the file with new lines but without using \n?
如何使用新行但不使用 \n 输出文件?
回答by Jon Skeet
The Windows way of terminating a line is to use "\r\n", not just "\n".
Windows 终止一行的方式是使用“\r\n”,而不仅仅是“\n”。
You can find the "line separator for the current operating system" using the line.separator
system property:
您可以使用line.separator
系统属性找到“当前操作系统的行分隔符” :
String lineSeparator = System.getProperty("line.separator");
...
StringBuilder builder = new StringBuilder();
...
builder.append(lineSeparator);
...
回答by GustyWind
You can get the value for the system your Java program is running on from the system properties
您可以从系统属性中获取运行 Java 程序的系统的值
public static String newline = System.getProperty("line.separator");
回答by khachik
You should add System.getProperty("line.separator")
instead of \n
. Since "nodepad", it is \r\n
, for MS Windows.
您应该添加System.getProperty("line.separator")
而不是\n
. 由于“nodepad”,它\r\n
适用于 MS Windows。
回答by Kozio?ek
In Windows you should use \n\r. In *NIX (Linux/UNIX/Mac) u should use \n
在 Windows 中,您应该使用 \n\r。在 *NIX (Linux/UNIX/Mac) 中,您应该使用 \n
回答by Jonathan
If you're using Windows, you should be writing \r\n
to get it to load properly in Notepad. The \n
terminator is a Unix file ending, and Notepad won't parse it properly. Wordpad will convert them for you.
如果您使用的是 Windows,您应该编写\r\n
以使其在记事本中正确加载。该\n
终止是一个Unix文件结尾,记事本将无法正确解析它。写字板将为您转换它们。
Also I suggest not using Notepad, and looking towards something like Vim.
另外我建议不要使用记事本,而寻找类似 Vim 的东西。