588

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Spoike
  • 119,724
  • 44
  • 140
  • 158

10 Answers10

756

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

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 8
    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. – Kon Mar 11 '16 at 23:22
  • 11
    @Kon Based on [this answer](http://stackoverflow.com/a/24946101/594137): `String.join("", Collections.nCopies(5, System.lineSeparator()))` – Samuel Harmer Mar 01 '17 at 11:05
  • 10
    With Java 11: `System.lineSeparator().repeat(5)` – Jacob G. Feb 03 '19 at 15:57
657

You can use

System.getProperty("line.separator");

to get the line separator

Keppil
  • 45,603
  • 8
  • 97
  • 119
abahgat
  • 13,360
  • 9
  • 35
  • 42
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.

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
Alex B
  • 24,678
  • 14
  • 64
  • 87
  • 8
    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" – Buttons840 Aug 26 '11 at 22:02
  • 45
    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. – abahgat Dec 16 '11 at 10:56
  • 4
    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' – Stealth Rabbi May 10 '13 at 15:02
  • 1
    @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 `%`. – Sean Allred Aug 06 '13 at 15:03
  • 7
    Don't use this if your string might contain `%` from user input! – Konstantin Weitz Nov 12 '13 at 21:09
  • @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. – hotshot309 Dec 03 '13 at 19:07
  • @KonstantinWeitz - Why not? The formatting routines don't double-process format substitutions. – Ted Hopp Dec 29 '13 at 16:40
  • @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. – Konstantin Weitz Dec 29 '13 at 19:32
  • @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.) – Ted Hopp Dec 29 '13 at 20:24
  • 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! – pyb Jun 30 '15 at 15:59
  • @abahgat Yes, but we're talking about Java here where verbosity is valued far more highly than elegance or conciseness – Basic Dec 10 '15 at 12:58
  • 10
    @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()`). – Franklin Yu May 05 '16 at 04:11
41

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

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
29

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

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

ceving
  • 21,900
  • 13
  • 104
  • 178
  • 8
    This is the same as Alex B's answer. – Spoike Apr 29 '13 at 07:49
  • 16
    Oh now I see it. He wrote so much unasked stuff around his answer. ;-) – ceving Apr 29 '13 at 10:07
  • I have tried doing this but when I viewed the file in notepad, it does not recognized the newline. – mr5 Jun 25 '15 at 06:43
  • 1
    @mr5 `notepad` is not the right tool to view the contents of a file. Use [`hexdump`](https://en.wikipedia.org/wiki/Hex_dump) or [`od`](https://en.wikipedia.org/wiki/Od_%28Unix%29). – ceving Jun 25 '15 at 12:18
  • @ceving I'm on a Windows environment and I was expecting the newline would be the combination of `\r\n` – mr5 Jun 25 '15 at 23:58
  • @mr5 To follow on from the comment form ceving: You can also use Notepad++, Sublime Text or VS code. All of these will work out if line endings are `'\n'` or `'\r\n'`. – Agi Hammerthief Aug 23 '18 at 07:49
23

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

hotshot309
  • 1,718
  • 1
  • 18
  • 20
lexicalscope
  • 7,158
  • 6
  • 37
  • 57
  • 21
    Yes, install a third party library just to get platform independant new line! #facepalm – Shervin Asgari Jan 07 '14 at 11:37
  • 26
    @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. – lexicalscope Jan 07 '14 at 16:06
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.

Sathesh
  • 486
  • 2
  • 12
  • 29
11

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.

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38
Damaji kalunge
  • 135
  • 1
  • 2
-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);
    }
}
sahlaysta
  • 95
  • 1
  • 3
-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( );
skiphoppy
  • 97,646
  • 72
  • 174
  • 218
Gary Davies
  • 920
  • 15
  • 12
  • 21
    This actually doesn't matter in most cases, [Coding Horror's Jeff Atwood made a blog post about this particular sort of micro-optimization](http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html). Always do metrics before making claims such as "don't do `string + string`". – Spoike Dec 05 '12 at 13:43
  • 6
    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. – Lajcik Dec 17 '12 at 14:22
  • 8
    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. – Richard Watson Jan 10 '13 at 10:48
  • 33
    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. – user327961 May 15 '13 at 12:48
  • 1
    @user327961: true story. One can easily prove this using your favourite IDE and a debugger. – Atmocreations Oct 10 '13 at 05:19