Platform-Independent Newline for Strings in Java

For any Java version:

private static final String BR = System.getProperty("line.separator");
// e.g.
String x = "a" + BR + "b";

Java 1.7 has a shortcut for this method:

private static final String BR = System.lineSeparator();
// e.g.
String x = "a" + BR + "b";

When formatting strings in Java 1.5 or higher there’s a nicer option:

// use String.format("%n"), e.g.
String x = String.format("a%nb");

Finally, to replace the arbitrary newline, with the one appropriate for current platform:

// use replaceAll("(\\r\\n|\\n\\r|\\r|\\n)+", ), e.g.
 
private static final String BR = System.getProperty("line.separator");
 
String correctNewline(String source)
{
    return source.replaceAll("(\\r\\n|\\n\\r|\\r|\\n)+", BR);
}
 
// Example:
 
String n = correctNewline("a\nb");    // Linux and Mac
String r = correctNewline("a\rb");    // Old Mac, nowadays usually a bug
String rn = correctNewline("a\r\nb"); // Windows
String nr = correctNewline("a\n\rb"); // Not a real sequence, but a common bug
Platform-Independent Newline for Strings in Java