问题:怎么样得到平台相关的换行符?
Java里面怎么样得到平台相关的换行符。我不可能到处都用"\n"
回答一
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
除了line.separator这个属性,如果你使用的是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 ^^
如果想知道得更多,那就去看看 Java 1.8 API关于Formatter的内容吧
回答二
Java 7 有一个 System.lineSeparator() 的方法
回答三
你可以使用
System.getProperty("line.separator");
去获取行分隔符
回答四
StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();
上面的代码会有两个字符串,被一个平台无关的换行分隔开
回答五
这是可行的:
String.format("%n").OrString.format("%n").intern()
去保存一些字符。
回答六
如果你尝试在文件中写入一个新行,你可以使用 BufferedWriter的newLine() 方法.
回答七
在commons-lang包下有一个常量域叫SystemUtils.LINE_SEPARATOR
回答八
如果你尝试写入一个文件,使用BufferedWriter实例,使用这个实例的newLine()方法。它提供一个平台无关的方法去在文件中写入一个新行。
文章翻译自Stack Overflow:https://stackoverflow.com/questions/207947/how-do-i-get-a-platform-dependent-new-line-character