Spoike
Spoike

Reputation: 121742

How do I get a platform-independent new line character?

How do I get a platform-independent newline in Java? I can’t use "\n" everywhere.

Upvotes: 595

Views: 462665

Answers (8)

sahlaysta
sahlaysta

Reputation: 135

Since JDK 1.1, the BufferedWriter class had the "newLine()" method which wrote the platform-dependent new line. It also provided the StringWriter class, making it possible to extract the new line:

public static String getSystemNewLine() {
    try {
        StringWriter sw = new StringWriter();
        BufferedWriter bw = new BufferedWriter(sw);
        bw.newLine();
        bw.flush();
        String s = sw.toString();
        bw.close();
        return s;
    } catch (Exception e) {
        throw new Error(e);
    }
}

Upvotes: -1

Sathesh
Sathesh

Reputation: 496

StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();

The above snippet will have two strings separated by a new line irrespective of platforms.

Upvotes: 16

Gary Davies
Gary Davies

Reputation: 960

Avoid appending strings using String + String etc, use StringBuilder instead.

String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );

Upvotes: -4

Alex B
Alex B

Reputation: 24926

In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting methods) you can use %n as in

Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c); 
//Note `%n` at end of line                                  ^^

String s2 = String.format("Use %%n as a platform independent newline.%n"); 
//         %% becomes %        ^^
//                                        and `%n` becomes newline   ^^

See the Java 1.8 API for Formatter for more details.

Upvotes: 377

StriplingWarrior
StriplingWarrior

Reputation: 156459

Java 7 now has a System.lineSeparator() method.

Upvotes: 765

abahgat
abahgat

Reputation: 13530

You can use

System.getProperty("line.separator");

to get the line separator

Upvotes: 659

lexicalscope
lexicalscope

Reputation: 7328

The commons-lang library has a constant field available called SystemUtils.LINE_SEPARATOR

Upvotes: 22

Michael Myers
Michael Myers

Reputation: 191855

If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.

Upvotes: 41

Related Questions