Java 如何获得依赖于平台的换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/207947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:23:16  来源:igfitidea点击:

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

javacross-platformnewlineeol

提问by Spoike

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

如何在 Java 中获得依赖于平台的换行符?我不能"\n"到处使用。

采纳答案by Alex B

In addition to the line.separator property, if you are using java 1.5 or later and the String.format(or other formattingmethods) you can use %nas in

除了line.separator属性,如果您使用的是Java 1.5或更高版本和的String.format(或其他格式化方法),可以使用%n

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 Formatterfor more details.

有关更多详细信息,请参阅Java 1.8 API for Formatter

回答by abahgat

You can use

您可以使用

System.getProperty("line.separator");

to get the line separator

获取行分隔符

回答by Michael Myers

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

如果您尝试将换行符写入文件,您可以简单地使用 BufferedWriter 的newLine()方法。

回答by Damaji kalunge

If you are writing to a file, using a BufferedWriterinstance, use the newLine()method of that instance. It provides a platform-independent way to write the new line in a file.

如果您正在使用BufferedWriter实例写入文件,请使用该实例的newLine()方法。它提供了一种独立于平台的方式来在文件中写入新行。

回答by lexicalscope

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

公地郎库有一个可用的恒定场称为SystemUtils.LINE_SEPARATOR

回答by StriplingWarrior

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

Java 7 现在有一个System.lineSeparator()方法。

回答by Gary Davies

Avoid appending strings using String + String etc, use StringBuilder instead.

避免使用 String + String 等附加字符串,而是使用 StringBuilder。

String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );

回答by ceving

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

这也是可能的:String.format("%n")

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

或者String.format("%n").intern()节省一些字节。

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

无论平台如何,上面的代码片段都有两个由新行分隔的字符串。