如何在Java中获得与平台相关的换行符?我到处都不能使用 "\n" .
"\n"
如果要使用 BufferedWriter 实例写入文件,请使用该实例的 newLine() 方法 . 它提供了一种独立于平台的方式来在文件中写入新行 .
BufferedWriter
newLine()
Java 7现在有一个System.lineSeparator()方法 .
StringBuilder newLine=new StringBuilder(); newLine.append("abc"); newline.append(System.getProperty("line.separator")); newline.append("def"); String output=newline.toString();
上面的代码片段将有两个由新行分隔的字符串,与平台无关 .
您可以使用
System.getProperty("line.separator");
得到行分隔符
如果你're trying to write a newline to a file, you could simply use BufferedWriter' s newLine()方法 .
除了line.separator属性之外,如果您使用的是java 1.5或更高版本以及 String.format (或其他 formatting 方法),则可以使用 %n ,如
%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 ^^
有关详细信息,请参阅Java 1.8 API for Formatter .
这也是可能的: String.format("%n") .
String.format("%n")
或 String.format("%n").intern() 保存一些字节 .
String.format("%n").intern()
commons-lang库有一个常量字段,名为SystemUtils.LINE_SEPARATOR
避免使用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( );
9 回答
如果要使用
BufferedWriter
实例写入文件,请使用该实例的newLine()
方法 . 它提供了一种独立于平台的方式来在文件中写入新行 .Java 7现在有一个System.lineSeparator()方法 .
上面的代码片段将有两个由新行分隔的字符串,与平台无关 .
您可以使用
得到行分隔符
如果你're trying to write a newline to a file, you could simply use BufferedWriter' s newLine()方法 .
除了line.separator属性之外,如果您使用的是java 1.5或更高版本以及 String.format (或其他 formatting 方法),则可以使用
%n
,如有关详细信息,请参阅Java 1.8 API for Formatter .
这也是可能的:
String.format("%n")
.或
String.format("%n").intern()
保存一些字节 .commons-lang库有一个常量字段,名为SystemUtils.LINE_SEPARATOR
避免使用String String等附加字符串,而是使用StringBuilder .