2

Suppose I have a string, which consists of a few lines:

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

I need to add character # to every line in the string as follows:

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

What is the easiest and portable (between Linux and Windows) way to do it Java ?

4

3 回答 3

5

Use the line.separator system property

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

These properties are described in more detail here.

If you open the source code for PrintWriter, you'll notice the following constructor:

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

It's getting (and using) the system specific separator to write to an OutputStream.

You can always set it at the property level

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

prints

ahaha: 

ahahahah:
#

All classes that request that property will now get {line.separator}#

于 2013-08-22T16:18:02.953 回答
2

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

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

输出:

first line
second line

System.outPrintStream支持这一点)。

于 2013-08-22T16:51:55.333 回答
1

从 Java 7 开始(也在此处注明),您还可以使用以下方法:

System.lineSeparator()

这与以下内容相同:

System.getProperty("line.separator")

获取系统相关的行分隔符字符串。下面引用官方JavaDocs中对该方法的描述:

返回系统相关的行分隔符字符串。它总是返回相同的值——系统属性 line.separator 的初始值。

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

于 2016-09-26T10:14:56.153 回答