怎么样得到平台相关的换行符?

问题:怎么样得到平台相关的换行符?

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").

Or

String.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值