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

JavaCross PlatformNewlineEol

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

You can use

System.getProperty("line.separator");

to get the line separator

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

This is also possible: String.format("%n").

Or String.format("%n").intern() to save some bytes.

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

If you are writing to a file, using a BufferedWriter instance, use the newLine() method of that instance. It provides a platform-independent way to write the new line in a file.

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpoikeView Question on Stackoverflow
Solution 1 - JavaStriplingWarriorView Answer on Stackoverflow
Solution 2 - JavaabahgatView Answer on Stackoverflow
Solution 3 - JavaAlex BView Answer on Stackoverflow
Solution 4 - JavaMichael MyersView Answer on Stackoverflow
Solution 5 - JavacevingView Answer on Stackoverflow
Solution 6 - JavalexicalscopeView Answer on Stackoverflow
Solution 7 - JavaSathesh Balakrishnan ManoharView Answer on Stackoverflow
Solution 8 - JavaDamaji kalungeView Answer on Stackoverflow
Solution 9 - JavaGary DaviesView Answer on Stackoverflow