【发布时间】:2013-08-25 12:05:19
【问题描述】:
假设我有一个字符串,它由几行组成:
aaa\nbbb\nccc\n(在 Linux 中)或 aaa\r\nbbb\r\nccc(在 Windows 中)我需要在字符串的每一行中添加字符#,如下所示:
什么是最简单且可移植(在 Linux 和 Windows 之间)的 Java 方式?
【问题讨论】:
假设我有一个字符串,它由几行组成:
aaa\nbbb\nccc\n(在 Linux 中)或 aaa\r\nbbb\r\nccc(在 Windows 中)我需要在字符串的每一行中添加字符#,如下所示:
什么是最简单且可移植(在 Linux 和 Windows 之间)的 Java 方式?
【问题讨论】:
使用line.separator 系统属性
String separator = System.getProperty("line.separator") + "#"; // concatenate the character you want
String myPortableString = "#aaa" + separator + "ccc";
这些属性有更详细的描述here。
如果您打开PrintWriter 的源代码,您会注意到以下构造函数:
public PrintWriter(Writer out,
boolean autoFlush) {
super(out);
this.out = out;
this.autoFlush = autoFlush;
lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
它正在获取(并使用)系统特定的分隔符以写入OutputStream。
您始终可以在属性级别进行设置
System.out.println("ahaha: " + System.getProperty("line.separator"));
System.setProperty("line.separator", System.getProperty("line.separator") + "#"); // change it
System.out.println("ahahahah:" + System.getProperty("line.separator"));
打印
ahaha:
ahahahah:
#
所有请求该属性的类现在都将获得{line.separator}#
【讨论】:
我不知道你到底在用什么,但是PrintWriter 的printf 方法可以让你编写格式化的字符串。使用字符串,您可以使用%n 格式说明符,它将输出特定于平台的行分隔符。
System.out.printf("first line%nsecond line");
输出:
first line
second line
(System.out 是 PrintStream,它也支持这个)。
【讨论】: