問題:怎么樣得到平臺相關的換行符?
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