This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Question: How do I get platform-specific newlines?
How to get platform-specific newlines in Java. I can’t use “\n” everywhere.
Answer a
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
Separator in addition to the line.separator property, you can use %n in string. format (or any other formatting method) if you use 1.5 or later
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 ^^
Copy the code
If you want to know more, check out the Java 1.8 API for Formatter
Answer two
Java 7 has a system.lineseparator () method
Answer three
You can use
System.getProperty("line.separator");
Copy the code
To get the line separator
Answer four
StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();
Copy the code
The above code will have two strings separated by a platform-independent newline
Answer five
It works:
String.format("%n").
Or
String.format("%n").intern()
Copy the code
To save some characters.
Answer 6
If you are trying to write a newLine to a file, you can use the BufferedWriter’s newLine() method.
Answer seven
In the commons-lang package there is a constant field called systemutils.line_separator
Answer eight
If you are trying to write to a file, use the BufferedWriter instance and use the newLine() method of that instance. It provides a platform-independent method to write a new line to a file.
The article translated from Stack Overflow:stackoverflow.com/questions/2…