我想逐行寫入文件到文件。 我有這個問題,這個過程需要很多時間,有時會得到canceld。目前的版本只是在最後把文件寫入文件。是否可以逐行寫入文件?寫入文件,但不只是在末尾
E.g.如果我在第4行(400)之後出現,則該文件當前爲空。但我想在文件中已經有了4行。
這裏是我的代碼:
String path = args[0];
String filename = args[1];
BufferedReader bufRdr = // this does not matter
BufferedWriter out = null;
FileWriter fstream;
try {
fstream = new FileWriter(path + "Temp_" + filename);
out = new BufferedWriter(fstream);
} catch (IOException e) {
System.out.println(e.toString());
}
String line = null;
try {
while ((line = bufRdr.readLine()) != null) {
// HERE I'm doing the writing with out.write
out.write(...);
}
} catch (IOException e) {
System.out.println(e.toString());
}
try {
out.close();
} catch (IOException e) {
System.out.println(e.toString());
}
刷新流以將內容保存到文件。雖然不建議繼續沖洗溪流。更好的是設置一個線的閾值(比如說每50線之後),在該點之後沖洗。 – 2013-05-08 08:33:23
另一方面,如果您尚未注意到它,bufRdr在使用之前需要初始化。 – mawia 2013-05-08 08:41:13