我創建了一個帶有一些標題的文本文件,然後關閉它,之後當我有數據寫入該文件時什麼也沒有發生,我的代碼在下面,堆棧當我嘗試打印時獲得的痕跡。我不能寫入我創建的文本文件
public class Writetofile {
BufferedWriter writer = null;
public void recordData(String record) throws IOException {
try {
writer.append(record);
writer.newLine();
writer.close();
} catch (Exception e) {e.printStackTrace();
}
}
public void createtxtfile(String[] details) throws IOException {
String machine = details[0];
String date = details[1];
String start_time = details[2];
try {
File new_cal = new File("C:\\Activity_Calibrator\\log\\" + machine + "//" + machine + ".txt");
new_cal.getParentFile().mkdirs();
FileWriter fwriter = new FileWriter(new_cal);
writer = new BufferedWriter(fwriter);
writer.append("Linear Calibration for " + machine + " carried out " + date);
writer.newLine();
writer.close();
} catch (Exception e) {
}
}
}
Message that is recieved
java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:116)
at java.io.BufferedWriter.write(BufferedWriter.java:221)
at java.io.Writer.write(Writer.java:157)
at java.io.Writer.append(Writer.java:227)
at Writetofile.recordData(Writetofile.java:27)
at UserInterFace.update(UserInterFace.java:75)
at Comms.serialEvent(Comms.java:124)
at gnu.io.RXTXPort.sendEvent(RXTXPort.java:732)
at gnu.io.RXTXPort.eventLoop(Native Method)
at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1575)
這很難理解,因爲我已經讀過,我應該在寫完之後總是關閉一個Stream。
永遠不要吞下任何異常,至少要對它忽略的原因留言。除了記錄和重新投擲它之外,絕對不要捕獲異常。永遠不要在任何代碼中使用'try {'...'} catch(Exception e){/ * empty * /};'即使調試也是如此,因爲您會在那裏忘記它並摧毀整個世界。 – hyde
好的,我已經這樣做了,可以看到它告訴我Stream已關閉,但在我讀到的所有地方,我都被告知應該在每次寫入時關閉Stream。 – DavyGravy
什麼方法調用引發異常?另外,請檢查文件名稱,是您認爲它是什麼? – hyde