Java 中的便携式换行符转换

Mic*_*ael 2 java string newline

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

aaa\nbbb\nccc\n(在 Linux 中)或 aaa\r\nbbb\r\nccc(在 Windows 中)

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

#aaa\n#bbb\n#ccc(在 Linux 中)或 #aaa\r\n#bbb\r\n#ccc(在 Windows 中)

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

Sot*_*lis 5

使用line.separator系统属性

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

此处更详细地描述了这些属性。

如果您打开 的源代码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"));
}
Run Code Online (Sandbox Code Playgroud)

它正在获取(并使用)系统特定的分隔符来写入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"));
Run Code Online (Sandbox Code Playgroud)

印刷

ahaha: 

ahahahah:
#
Run Code Online (Sandbox Code Playgroud)

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