2012-01-31 58 views
0

我有一個文本文件,其中包含數據庫表數據,並試圖刪除表的一部分。這是該文件中:基本的java I/O文本替換,沒有得到預期的輸出

name= john 
name= bill 
name= tom 
name= bob 
name= mike 

這裏是編譯和運行我的Java代碼,但輸出是不是我所期待和堅持。

import java.io.*; 
public class FileUtil { 

    public static void main(String args[]) { 

     try { 

      FileInputStream fStream = new FileInputStream("\\test.txt"); 
      BufferedReader in = new BufferedReader(new InputStreamReader(fStream)); 


      while (in.ready()) { 
       //System.out.println(in.readLine()); 
       String line = in.readLine(); 
       String keyword = "name="; //keyword to delete in txt file 
       String newLine=line.replaceAll(keyword,""); //delete lines that say name= 
       BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt")); 
       out.write(newLine.getBytes()); 
       out.close(); 

      } 
      in.close(); 

     } catch (IOException e) { 
      System.out.println("File input error"); 
     } 

    } 
} 

在testEdited文件的輸出是這樣的:

邁克

顯然我想只剩下5名。誰能幫我嗎? 感謝

+1

您的'新的FileOutputStream'將始終寫入文件開頭的數據。考慮使用另外一個將append作爲布爾參數的構造函數。或者在頂部打開一次,然後在程序結束時關閉一次。哦,這是功課嗎? – 2012-01-31 02:07:56

+0

不,我要創建這個程序來幫助一個不同類的數據挖掘項目,我需要刪除不需要的表數據,並試圖刷我的Java。 – user1170757 2012-01-31 02:10:39

回答

2

試試這個:

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt",true)); 

true將數據添加到您的文件。

+1

非常感謝。這就是我需要的。 – user1170757 2012-01-31 02:56:32

0

對於並行讀寫操作,不能使用BufferedInputStream/BufferedOutputStream。 如果您想要同時讀取和寫入文件,請使用RandomAccessFile

+0

dest文件與源文件不同。 – Bill 2012-01-31 02:21:09

+0

哎呀..謝謝你指出比爾。 – NiranjanBhat 2012-01-31 03:54:51

2

嘗試......

 String line; 
     BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt")); 

     while ((line = in.readLine()) != null) { 
      String newLine=line.replaceAll("name=",""); 
      out.write(newLine.getBytes()); 
     } 
     out.close(); 
     in.close(); 

沒有必要繼續打開和關閉輸出文件。

另外關於「name =」聲明,分配給變量沒有多少意義,只能在緊隨其後的行上使用它。如果它需要是一個共享的常量,請在某個類的某個類中聲明它爲(private|public) static final String foo = "bar";

此外,將文件輸出流(或文件寫入器)封裝在適當的緩衝版本中沒有太多好處,操作系統會自動爲您緩衝寫入,並且在此方面做得很好。

您還應該用讀取器替換您的流並在finally塊中關閉文件。