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 ?

Michael
  • 41,026
  • 70
  • 193
  • 341

3 Answers3

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}#

rolfl
  • 17,539
  • 7
  • 42
  • 76
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
2

I don't know what exactly you are using, but PrintWriter's printf methods lets you write formatted strings. Withing the string you can use the %n format specifier which will output the platform specific line separator.

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

The output:

first line
second line

(System.out is a PrintStream which also supports this).

Katona
  • 4,816
  • 23
  • 27
1

As of Java 7 (also noted here) you can also use the method:

System.lineSeparator()

which is the same as:

System.getProperty("line.separator")

to get the system-dependent line separator string. The description of the method from the official JavaDocs is quoted below:

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.

On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

Community
  • 1
  • 1
pgmank
  • 5,303
  • 5
  • 36
  • 52