我创建了一个包含一些标题的文本文件,然后将其关闭,之后当我有数据要写入该文件时没有任何反应,我的代码在下面,当我尝试打印到它时我得到的堆栈跟踪
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。
答案 0 :(得分:5)
没有任何反应,我没有收到错误
一个好的第一步就是不要吞下异常 - 例如你可以将堆栈跟踪打印到控制台:
} catch (Exception e) {
e.printStackTrace();
}
然后您将收到一条正确的异常消息,该消息可帮助您找到问题。
答案 1 :(得分:1)
在此行中,您将"//"
添加到路径:
File new_cal = new File("C:\\Activity_Calibrator\\log\\" + machine + "//" + machine + ".txt");
您可能想要添加"\\"
。
我认为这会弄乱文件创建,但我不确定如何不测试。它甚至可能依赖于操作系统。打印File.getCanonicalFile()
确认的文件名。