如何在Java中获得一个依赖于平台的换行符?我不能到处都用“\n”。
除了行。如果您使用的是java 1.5或更高版本,则使用String. separator属性。格式(或其他格式化方法),您可以使用%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 ^^
有关更多细节,请参阅用于Formatter的Java 1.8 API。
避免使用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( );
StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();
上面的代码段将有两个字符串,由新行分隔,与平台无关。
从JDK 1.1开始,BufferedWriter类就有了"newLine()"方法,用于编写依赖于平台的新行。它还提供了StringWriter类,使得提取新行成为可能:
public static String getSystemNewLine() {
try {
StringWriter sw = new StringWriter();
BufferedWriter bw = new BufferedWriter(sw);
bw.newLine();
bw.flush();
String s = sw.toString();
bw.close();
return s;
} catch (Exception e) {
throw new Error(e);
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap