2009-07-15 58 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

相關問題