java lineseparator,System.lineSeparator()什么都不返回

博客探讨了Java中使用System.getProperty(\line.separator\)和System.lineSeparator()输出换行符时显示为空的问题。解释了换行符包含特殊字符,打印时不会显示转义序列。还给出解决方案,可使用Apache Commons的escapeJava方法查看转义后的换行符。

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值