我有一個文本文件,其中包含數據庫表數據,並試圖刪除表的一部分。這是該文件中:基本的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名。誰能幫我嗎? 感謝
您的'新的FileOutputStream'將始終寫入文件開頭的數據。考慮使用另外一個將append作爲布爾參數的構造函數。或者在頂部打開一次,然後在程序結束時關閉一次。哦,這是功課嗎? – 2012-01-31 02:07:56
不,我要創建這個程序來幫助一個不同類的數據挖掘項目,我需要刪除不需要的表數據,並試圖刷我的Java。 – user1170757 2012-01-31 02:10:39