System.lineSeparator() returns nothing

蓝咒 提交于 2019-12-22 22:47:11

问题


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?

I use windows 7, eclipse and jdk 1.8.


回答1:


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");

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.


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);
    }
}

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

javac -cp commons-lang3-3.4.jar LineSeparators.java
java -cp commons-lang3-3.4.jar:. LineSeparators



回答2:


Printing something afterwards will show the effect:

System.out.println("a" + System.lineSeparator() + "b");

Gives

a
b


来源:https://stackoverflow.com/questions/31984415/system-lineseparator-returns-nothing

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