System.lineSeparator()什么都不返回 [英] System.lineSeparator() returns nothing
问题描述
使用以下内容时应该看到什么?
What should I see when I use the following?
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
System.out.println("LineSeperator2: "+System.lineSeparator());
我得到以下回报:
LineSeperator1:
LineSeperator2:
它是空的吗?无形?应该有类似 \ r或\ n
的东西?
Is it empty? invisible? shouldn there be something like \r or \n
?
我使用的是Windows 7,eclipse和jdk 1.8 。
I use windows 7, eclipse and jdk 1.8.
推荐答案
正如您所料,行分隔符包含特殊字符,例如'\ r'
或'\ n'
表示一行的结尾。但是,尽管它们将使用那些反斜杠转义序列用Java源代码编写,但它们在打印时不会出现这种情况。行分隔符的目的是分隔行,例如,
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
System.out.println("Hello"+System.lineSeparator()+"World");
Hello
World
而不是说
Hello\nWorld
你甚至可以在你的代码输出中看到这个:输出
You can even see this in the output of your code: the output of
System.out.println("LineSeperator1: "+System.getProperty("line.separator"));
在下一个语句的输出之前有一个额外的空行,因为有一个行分隔符来自 System.getProperty(line.separator)
和另一个使用 println
。
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
.
如果你真的想看看行分隔符的转义版本是什么样的,你可以使用 escapeJava来自 Apache Commons 的
。例如:
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:
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);
}
}
在我的系统上,输出
LineSeparator1: \n
LineSeparator2: \n
请注意,我必须在与 Apache下载,使用这些命令进行编译和运行
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
javac -cp commons-lang3-3.4.jar LineSeparators.java
java -cp commons-lang3-3.4.jar:. LineSeparators
这篇关于System.lineSeparator()什么都不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!