ChatGPT解决这个技术问题 Extra ChatGPT

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

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

Please consider changing the accepted answers. The 2nd answer is more appropriate.

L
Luiggi Mendoza

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


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 Based on this answer: String.join("", Collections.nCopies(5, System.lineSeparator()))
With Java 11: System.lineSeparator().repeat(5)
@JacobG Stop gloating.. some of us are still stuck on Java 7.
@AndrewTFinnell I would find a better job <:-P No containers -> no Java 11, so you are staying for better salary, we can gloat :-D
K
Keppil

You can use

System.getProperty("line.separator");

to get the line separator


Care to add Java 7 System.lineSeparator() details so here is a definitive answer to this question?
B
Brian McCutchon

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.


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"
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.
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'
Don't use this if your string might contain % from user input!
@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()).
M
Michael Myers

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


c
ceving

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

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


This is the same as Alex B's answer.
Oh now I see it. He wrote so much unasked stuff around his answer. ;-)
I have tried doing this but when I viewed the file in notepad, it does not recognized the newline.
@mr5 notepad is not the right tool to view the contents of a file. Use hexdump or od.
@ceving I'm on a Windows environment and I was expecting the newline would be the combination of \r\n
h
hotshot309

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


Yes, install a third party library just to get platform independant new line! #facepalm
@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.
This is indeed a good suggestion for projects that are already using this library, thanks!
S
Sathesh Balakrishnan Manohar
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.


A
Agi Hammerthief

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.


This answer is a duplicate of Mike Meyers'.
s
skiphoppy

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

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".
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, 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.
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: true story. One can easily prove this using your favourite IDE and a debugger.