2009-07-15 69 views
2

我试图编写一个程序来操纵从文件中读入的unicode字符串。我想到了两种方法 - 一种是在其中读取包含换行符的整个文件,执行几次regex替换,然后将其写回另一个文件;另一个是我逐行读取文件并匹配个别行并替换它们并将其写出。我还没有能够测试第一种方法,因为字符串中的换行符不被写为文件的换行符。下面是一些示例代码来说明:字符串中的换行符不写出来的文件

String output = "Hello\nthere!"; 
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("test.txt"), "UTF-16")); 

System.out.println(output); 
oFile.write(output); 
oFile.close(); 

print语句输出

你好
那里!

但文件内容

Hellothere!

为什么不把我的换行符写入文件?

+3

记事本无法正确显示仅有\ n的文本文件。 – akarnokd 2009-07-15 18:39:14

+0

看看它是否仍然与\ r \ n – 2009-07-15 18:42:10

回答

9

你应该尝试使用

System.getProperty("line.separator") 

下面是一个未经测试的例子

String output = String.format("Hello%sthere!",System.getProperty("line.separator")); 
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("test.txt"), "UTF-16")); 

System.out.println(output); 
oFile.write(output); 
oFile.close(); 

我一直没能考第一 方法,因为在 串的换行不写成新行至 档案

你确定吗?你可以发布一些代码来显示特定的事实吗?

1

使用System.getProperty(“line.separator”)来获取特定于平台的换行符。

1

考虑使用PrintWriters来获取从例如已知的println方法。 System.out