Java中的便携式换行转换

时间:2013-08-22 16:17:14

标签: java string newline

假设我有一个字符串,它由几行组成:

aaa\nbbb\nccc\n (in Linux) or aaa\r\nbbb\r\nccc (in Windows)

我需要在字符串的每一行添加字符#,如下所示:

#aaa\n#bbb\n#ccc (in Linux) or #aaa\r\n#bbb\r\n#ccc (in Windows)

什么是最简单的便携式(在Linux和Windows之间)做Java的方式?

3 个答案:

答案 0 :(得分:4)

使用line.separator系统属性

String separator = System.getProperty("line.separator") + "#"; // concatenate the character you want
String myPortableString = "#aaa" + separator + "ccc";

更详细地描述了这些属性here

如果您打开PrintWriter的源代码,您会注意到以下构造函数:

public PrintWriter(Writer out,
                   boolean autoFlush) {
    super(out);
    this.out = out;
    this.autoFlush = autoFlush;
    lineSeparator = java.security.AccessController.doPrivileged(
        new sun.security.action.GetPropertyAction("line.separator"));
}

正在获取(并使用)特定于系统的分隔符以写入OutputStream

您始终可以在属性级别设置

System.out.println("ahaha: " + System.getProperty("line.separator"));
System.setProperty("line.separator", System.getProperty("line.separator") + "#"); // change it
System.out.println("ahahahah:" + System.getProperty("line.separator"));

打印

ahaha: 

ahahahah:
#

请求该属性的所有类现在都将获得{line.separator}#

答案 1 :(得分:2)

我不知道你到底在用什么,但是PrintWriterprintf方法可以让你编写格式化的字符串。使用字符串,您可以使用%n格式说明符,它将输出特定于平台的行分隔符。

System.out.printf("first line%nsecond line");

输出:

first line
second line

System.outPrintStream,也支持此功能。)

答案 2 :(得分:1)

从Java 7(也称为here)开始,您也可以使用以下方法:

System.lineSeparator()

与:

相同
System.getProperty("line.separator")

获取系统相关的行分隔符字符串。 来自官方JavaDocs的方法说明如下:

  

返回依赖于系统的行分隔符字符串。它总是回归   相同的值 - 系统属性的初始值   line.separator。

     

在UNIX系统上,它返回“\ n”;在Microsoft Windows系统上   返回“\ r \ n”。