2013-01-05 15 views
1

後,我有內容的文本文件:如何保持在同一格式的文本文件的內容替換字符串

love 
test 
me 
once 

我的Java程序通過「利物浦」取代了「愛」字。但是文本文件丟失了它的格式並且變成這樣:

Liverpool test me once 

所有字符串出現在一行上。

這是我到目前爲止有:

import java.io.*; 
public class Replace_Line { 
public static void main(String args[]) { 
    try { 
     File file = new File("C:\\Users\\Antish\\Desktop\\Test_File.txt"); 
     BufferedReader reader = new BufferedReader(new FileReader(file)); 
     String line = "", oldtext = ""; 
     while ((line = reader.readLine()) != null) { 
      oldtext += line + " "; 
     } 
     reader.close(); 
     // replace a word in a file 
     // String newtext = oldtext.replaceAll("boy", "Love"); 

     // To replace a line in a file 
     String newtext = oldtext.replaceAll("love", "Liverpool"); 

     FileWriter writer = new FileWriter(
       "C:\\Users\\Antish\\Desktop\\Test_File.txt"); 
     writer.write(newtext); 
     writer.close(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } 
} 
} 

任何幫助,以保持文件格式相同,只是替換字符串。 感謝

回答

1

你失去換行符在閱讀這樣的:

while((line = reader.readLine()) != null) { 
    oldtext += line + " "; 
} 

爲了解決這個問題,你應該

oldtext += line + "\n"; 

替換代碼內環路但要知道​​的事實,逐行讀取文件並將每行連接到+=效率非常低。學習Java時可以這樣做,但不能在任何生產代碼中使用。使用StringBuilder或某些外部庫來處理IO。

1

當您按行讀取時,您將刪除所有換行符,然後用空格替換它們。

oldtext += line + " "; 

有待

oldtext += line + System.lineSeparator(); 
+0

感謝system.lineSeperator()的工作 – Deathstar

0

更換

oldtext += line + " "; 

通過

oldtext += line + "\n"; 

注意,這將改變新行字符(可能是\ R或\ r \ n)由一個\ n雖然。還要注意,在一個循環中使用+運算符進行連接是非常低效的,因爲它會產生大量的大量不需要的STring實例。你最好使用StringBuilder或StringWriter。

爲什麼不簡單地將整個文件作爲單個字符串讀取,然後調用replaceAll並重寫所有內容。請參閱Guava's methodcommons-io method

相關問題