2013-04-09 44 views
0

我已經看到很多關於此的帖子,但我無法做到這一點。我需要做這樣的事情..可以說, 我有兩個文件a.txt,b.txt。 我應該在a.txt中搜索一個字符串/行,並將其替換爲b.txt的內容。 我認爲它的幾行簡單的代碼。我試了下面的代碼,但它不工作...Java:查找並替換一條線

File func = new File("a.txt"); 
BufferedReader br = new BufferedReader(new FileReader(func)); 

String line; 

while ((line = br.readLine()) != null) { 
    if (line.matches("line to replace")) { 
     br = new BufferedReader(
       new FileReader(func)); 
     StringBuffer whole = new StringBuffer(); 
     while ((line = br.readLine()) != null) { 
      whole.append(line.toString() + "\r\n"); 
     } 
     whole.toString().replace("line to replace", 
       "b.txt content"); 
     br.close(); 

     FileWriter writer = new FileWriter(func); 
     writer.write(whole.toString()); 
     writer.close(); 
     break; 
    } 
} 
br.close(); 

請幫忙!

+0

'writer.close();'和'br.close();'應該在while循環之外。另外,你應該在循環之外創建'writer'和'br'。 – Maroun 2013-04-09 13:48:47

回答

0

這裏是解決這一問題的技術:

  1. 打開閱讀的A.TXT文件。
  2. 打開b.txt文件進行閱讀。
  3. 打開名爲a.new.txt的輸出文件。
  4. 從a.txt文件讀取一行。
  5. 如果該行不是所需的行(要替換的行),請將行寫入輸出文件,然後執行步驟4.
  6. 將b.txt文件的內容附加到輸出文件。
  7. 將a.txt的剩餘內容附加到輸出文件。
0

嗯......也許你能避免剛好與字符串類創建工作BufferedReader類的實例和:

public class Sample { 

public static void main(String[] args) throws Exception{ 
    File afile = new File("/home/mtataje/a.txt"); 

    String aContent = getFileContent(afile); 
    System.out.println("A content: "); 
    System.out.println(aContent); 
    System.out.println("==================="); 
    if (aContent.contains("java rulez")) { 
     File bfile = new File("/home/mtataje/b.txt"); 
     String bContent = getFileContent(bfile); 
     String myString = aContent.replace("java rulez", bContent); 
     System.out.println("New content: "); 
     System.out.println(myString); 
     afile.delete();//delete old file 
     writeFile(myString);//I replace the file by writing a new one with new content 
    } 
} 

public static void writeFile(String myString) throws IOException { 
    BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/a.txt"))); 
    bw.write(myString); 
    bw.close(); 
} 

public static String getFileContent(File f) throws IOException { 
    BufferedReader br = new BufferedReader(new FileReader(f)); 

    String line; 
    StringBuffer sa = new StringBuffer(); 
    while ((line = br.readLine()) != null) { 
     sa.append(line); 
     sa.append("\n"); 
    } 
    br.close(); 
    return sa.toString(); 
} 

我剛剛分開,以避免讀取文件兩次的方法相同的代碼塊。我希望它能幫助你,或者至少可以幫助你滿足你的要求。最好的祝福。

+0

謝謝,我可以將b.txt中的內容複製到a.txt中,但是當我打開文件a.txt時,它沒有任何更改......只有在控制檯中顯示替換的內容,但是實際的文件沒有得到保存。任何想法? – 2013-04-10 03:44:34

+0

我修改了代碼,以便爲您提供一種可以保存更換中所做更改的方式。最好的祝福。 – 2013-04-10 13:09:37