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

8

592

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

Protrusion answered 16/10, 2008 at 9:37 Comment(0)
D
377

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.

Demarcusdemaria answered 16/10, 2008 at 18:45 Comment(11)
Thank you! I'm sure System.getProperty("line.separator"); has its uses, but I get tired of seeing: "Line 1" + System.getProperty("line.separator") + "Line 2"Unclean
Oh my, "Line 1" + System.getProperty("line.separator") + "Line 2" is indeed one of the ugliest things I've ever seen. Just declaring a constant elsewhere would be less painful.Kunlun
this doesn't work, at least, with a string going in to a log4j statement. Creating an example with a newline at the end is potentially hiding the problem. Also, the String s2 is just confusing using '%%n'Haskins
@StealthRabbi It is common in (at least) C-like languages to 'escape the escape character' to insert the literal character, e.g. . \\ . (less the dots) produces a single backslash and %% produces a single %.Lymphadenitis
Don't use this if your string might contain % from user input!Lacquer
@SeanAllred, that's true...but I think @StealthRabbi was saying it is unclear in the example above (at least on first reading) what the %%n is supposed to mean. In any case, the formatted text is supposed to read, "Use %n as a platform independent newline." with a newline character at the end.Bigamous
@KonstantinWeitz - Why not? The formatting routines don't double-process format substitutions.Cathead
@Ted Hopp, if s is a user provided string, you should not use it in the format string, e.g. format(s+"%n"), because if s contains % this will fail. It is fine to use user provided strings as format arguments.Lacquer
@KonstantinWeitz - Well, using a user-supplied string is always risky. The example you provide will only fail if the string contains an unescaped % as the final character. But in that case, the format would be invalid if you used s+"\n". (Which would you rather have when the user supplies such a format string--an exception or a missing newline? I think it's a toss-up.)Cathead
If you're building a String and using line breaks to separate lines, you want to test that your text is not empty so you don't end up with just line breaks. Otherwise that's a good tip!Mirthamirthful
@KonstantinWeitz, the problem of String.format(s + "%n") is easily solved by String.format("%s%n", s). It is always risky to involve user input as format body (in the same way as eval()).Footless
F
760

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

Fortyniner answered 7/6, 2012 at 18:5 Comment(3)
Would have been very nice of them to provide an overloaded method lineSeperator(int) which returns some number of line seperators, as I often find myself using 2 at once.Checkerboard
@Checkerboard Based on this answer: String.join("", Collections.nCopies(5, System.lineSeparator()))Gaylagayle
With Java 11: System.lineSeparator().repeat(5)Brakpan
K
658

You can use

System.getProperty("line.separator");

to get the line separator

Kunlun answered 16/10, 2008 at 9:39 Comment(0)
D
377

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.

Demarcusdemaria answered 16/10, 2008 at 18:45 Comment(11)
Thank you! I'm sure System.getProperty("line.separator"); has its uses, but I get tired of seeing: "Line 1" + System.getProperty("line.separator") + "Line 2"Unclean
Oh my, "Line 1" + System.getProperty("line.separator") + "Line 2" is indeed one of the ugliest things I've ever seen. Just declaring a constant elsewhere would be less painful.Kunlun
this doesn't work, at least, with a string going in to a log4j statement. Creating an example with a newline at the end is potentially hiding the problem. Also, the String s2 is just confusing using '%%n'Haskins
@StealthRabbi It is common in (at least) C-like languages to 'escape the escape character' to insert the literal character, e.g. . \\ . (less the dots) produces a single backslash and %% produces a single %.Lymphadenitis
Don't use this if your string might contain % from user input!Lacquer
@SeanAllred, that's true...but I think @StealthRabbi was saying it is unclear in the example above (at least on first reading) what the %%n is supposed to mean. In any case, the formatted text is supposed to read, "Use %n as a platform independent newline." with a newline character at the end.Bigamous
@KonstantinWeitz - Why not? The formatting routines don't double-process format substitutions.Cathead
@Ted Hopp, if s is a user provided string, you should not use it in the format string, e.g. format(s+"%n"), because if s contains % this will fail. It is fine to use user provided strings as format arguments.Lacquer
@KonstantinWeitz - Well, using a user-supplied string is always risky. The example you provide will only fail if the string contains an unescaped % as the final character. But in that case, the format would be invalid if you used s+"\n". (Which would you rather have when the user supplies such a format string--an exception or a missing newline? I think it's a toss-up.)Cathead
If you're building a String and using line breaks to separate lines, you want to test that your text is not empty so you don't end up with just line breaks. Otherwise that's a good tip!Mirthamirthful
@KonstantinWeitz, the problem of String.format(s + "%n") is easily solved by String.format("%s%n", s). It is always risky to involve user input as format body (in the same way as eval()).Footless
M
41

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

Messer answered 16/10, 2008 at 18:49 Comment(0)
P
23

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

Pinnati answered 28/3, 2012 at 16:33 Comment(2)
Yes, install a third party library just to get platform independant new line! #facepalmHylotheism
@Shervin of course you would not do that, but many projects I have worked on are already using commons-lang and some older version of Java. So if you happen to be using commons-lang already then this is a sensible answer. I didn't feel it necessary to point that out, I was obviously wrong.Pinnati
D
16
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.

Diploblastic answered 29/9, 2015 at 11:20 Comment(0)
W
-2

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);
    }
}
Washy answered 7/10, 2022 at 18:10 Comment(0)
E
-5

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( );
Equalizer answered 5/12, 2012 at 8:53 Comment(5)
This actually doesn't matter in most cases, Coding Horror's Jeff Atwood made a blog post about this particular sort of micro-optimization. Always do metrics before making claims such as "don't do string + string".Protrusion
I'd say that Jeff's article may be a bit off since it only touches on execution time. String concatenation in Java is not only about execution speed but also how much garbage you leave in memory for the GC to clean, which may result in the GC running more often. This might or might not be an issue depending on your environment and configuration.Mainsail
Lajcik, I suspect that's pre-optimization for all cases except those who really do a lot of string manipulation. The StringBuffer is an anti-pattern for minor concatenation requirements. In many cases I'd rather have readable String1 + separator + String2 than the abovementioned multi-line example. Besides, I'd suggest testing whether memory & GC is impacted positively by adding the SB. In many cases I'd guess it isn't. If it's not worth testing, it's probably pre-optimizing and I'd focus on readability.Ist
Doing a String1 + String2 is the same as doing new StringBuilder(String1).append(String2) in modern compilers, so there is no optimization at all for a one liner string concat. StringBuilder is generaly worth it only in loops or recursive methods. But anyway, this might be out of the scope of the original question.Studio
@user327961: true story. One can easily prove this using your favourite IDE and a debugger.Fortress

© 2022 - 2024 — McMap. All rights reserved.