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

限于喜欢 提交于 2019-11-25 22:27:03

问题


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


回答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.




回答2:


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




回答3:


You can use

System.getProperty("line.separator");

to get the line separator




回答4:


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




回答5:


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

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




回答6:


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




回答7:


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.




回答8:


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.




回答9:


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


来源:https://stackoverflow.com/questions/207947/how-do-i-get-a-platform-dependent-new-line-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!