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

445,053

Solution 1

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 2

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

Solution 3

You can use

System.getProperty("line.separator");

to get the line separator

Solution 4

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

Solution 5

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

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

Share:
445,053
Troj
Author by

Troj

I'm a jack of most trades residing in Sweden and usually involved with full-stack web development technologies. I work for tretton37 as a contractor, my list of clients includes among others Sony and IKEA. I dabble in open source software and have many projects in my Github repository and my Bitbucket repository, among many: RefluxJS - Library for uni-directional data flows, inspired by Facebook's Flux In the little free time that I have, all kinds of stuff happen such as drawing pretty pictures, perform ball juggling, play a guitar, hack on games, and solve a Rubik's cube.

Updated on August 23, 2020

Comments

  • Troj
    Troj almost 4 years

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

    • Gray
      Gray almost 6 years
      Please consider changing the accepted answers. The 2nd answer is more appropriate.
  • Buttons840
    Buttons840 almost 13 years
    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"
  • user2756501
    user2756501 over 12 years
    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.
  • Troj
    Troj over 11 years
    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".
  • Lajcik
    Lajcik over 11 years
    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.
  • Richard Watson
    Richard Watson over 11 years
    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.
  • Troj
    Troj about 11 years
    This is the same as Alex B's answer.
  • ceving
    ceving about 11 years
    Oh now I see it. He wrote so much unasked stuff around his answer. ;-)
  • Stealth Rabbi
    Stealth Rabbi about 11 years
    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'
  • user327961
    user327961 about 11 years
    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.
  • Sean Allred
    Sean Allred almost 11 years
    @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 %.
  • Atmocreations
    Atmocreations over 10 years
    @user327961: true story. One can easily prove this using your favourite IDE and a debugger.
  • Konstantin Weitz
    Konstantin Weitz over 10 years
    Don't use this if your string might contain % from user input!
  • hotshot309
    hotshot309 over 10 years
    @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.
  • Ted Hopp
    Ted Hopp over 10 years
    @KonstantinWeitz - Why not? The formatting routines don't double-process format substitutions.
  • Konstantin Weitz
    Konstantin Weitz over 10 years
    @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.
  • Ted Hopp
    Ted Hopp over 10 years
    @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.)
  • Shervin Asgari
    Shervin Asgari over 10 years
    Yes, install a third party library just to get platform independant new line! #facepalm
  • lexicalscope
    lexicalscope over 10 years
    @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.
  • Alexis Leclerc
    Alexis Leclerc about 10 years
    This is indeed a good suggestion for projects that are already using this library, thanks!
  • mr5
    mr5 almost 9 years
    I have tried doing this but when I viewed the file in notepad, it does not recognized the newline.
  • ceving
    ceving almost 9 years
    @mr5 notepad is not the right tool to view the contents of a file. Use hexdump or od.
  • mr5
    mr5 almost 9 years
    @ceving I'm on a Windows environment and I was expecting the newline would be the combination of \r\n
  • pyb
    pyb almost 9 years
    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!
  • Basic
    Basic over 8 years
    @abahgat Yes, but we're talking about Java here where verbosity is valued far more highly than elegance or conciseness
  • Kon
    Kon about 8 years
    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.
  • Franklin Yu
    Franklin Yu about 8 years
    @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()).
  • Samuel Harmer
    Samuel Harmer over 7 years
    @Kon Based on this answer: String.join("", Collections.nCopies(5, System.lineSeparator()))
  • Gray
    Gray almost 6 years
    Care to add Java 7 System.lineSeparator() details so here is a definitive answer to this question?
  • Agi Hammerthief
    Agi Hammerthief almost 6 years
    @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
    Agi Hammerthief almost 6 years
    This answer is a duplicate of Mike Meyers'.
  • Jacob G.
    Jacob G. over 5 years
    With Java 11: System.lineSeparator().repeat(5)
  • Andrew T Finnell
    Andrew T Finnell over 5 years
    @JacobG Stop gloating.. some of us are still stuck on Java 7.
  • Aubergine
    Aubergine over 4 years
    @AndrewTFinnell I would find a better job <:-P No containers -> no Java 11, so you are staying for better salary, we can gloat :-D