java System.lineSeparator() 不返回任何内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31984415/
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
System.lineSeparator() returns nothing
提问by Gero
What should I see when I use the following?
当我使用以下内容时,我应该看到什么?
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
System.out.println("LineSeperator2: "+System.lineSeparator());
I get the following back:
我得到以下回复:
LineSeperator1:
LineSeperator2:
Is it empty? invisible? shouldn there be something like \r or \n
?
是空的吗?无形的?应该有类似的东西\r or \n
吗?
I use windows 7, eclipse and jdk 1.8.
我使用 windows 7、eclipse 和 jdk 1.8。
回答by Alden
As you expect, the line separator contains special characters such as '\r'
or '\n'
that denote the end of a line. However, although they would be written in Java source code with those backslash escape sequences, they do not appear that way when printed. The purpose of a line separator is to separate lines, so, for example, the output of
如您所料,行分隔符包含特殊字符,例如'\r'
或'\n'
表示行尾。然而,尽管它们是用 Java 源代码编写的,带有那些反斜杠转义序列,但在打印时它们不会那样显示。行分隔符的目的是分隔行,例如,输出
System.out.println("Hello"+System.lineSeparator()+"World");
is
是
Hello
World
rather than, say
而不是说
Hello\nWorld
You can even see this in the output of your code: the output of
您甚至可以在代码的输出中看到这一点:
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
had an extra blank line before the output of the next statement, because there was a line separator from System.getProperty("line.separator")
and another from the use of println
.
在下一条语句的输出之前有一个额外的空行,因为有一个行分隔符 fromSystem.getProperty("line.separator")
和另一个 from 的使用println
。
If you really want to see what the escaped versions of the line separators look like, you can use escapeJava
from Apache Commons. For example:
如果您真的想查看行分隔符的转义版本是什么样的,您可以使用escapeJava
from Apache Commons。例如:
import org.apache.commons.lang3.StringEscapeUtils;
public class LineSeparators {
public static void main(String[] args) {
String ls1 = StringEscapeUtils.escapeJava(System.getProperty("line.separator"));
System.out.println("LineSeperator1: "+ls1);
String ls2 = StringEscapeUtils.escapeJava(System.lineSeparator());
System.out.println("LineSeperator2: "+ls2);
}
}
On my system, this outputs
在我的系统上,这输出
LineSeparator1: \n
LineSeparator2: \n
Note that I had to run it in the same folder as the .jar file from the Apache download, compiling and running with these commands
请注意,我必须在与Apache 下载的 .jar 文件相同的文件夹中运行它,使用这些命令编译和运行
javac -cp commons-lang3-3.4.jar LineSeparators.java
java -cp commons-lang3-3.4.jar:. LineSeparators
回答by weston
Printing something afterwards will show the effect:
之后打印一些东西会显示效果:
System.out.println("a" + System.lineSeparator() + "b");
Gives
给
a
b