【发布时间】:2016-12-02 22:13:46
【问题描述】:
我正在尝试从 txt 文件中读取学生地图,然后我将新学生添加到地图中(现在比以前大)并将其保存回文件中。在我关闭程序并从文件中重新加载数据后,新学生没有保存。
HashMap<String, Student> studentObj = new HashMap<>(SIZE);
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME));
studentObj = (HashMap<String, Student>) in.readObject();
studentObj.put(student.getStudentID(), student);
ObjectOutputStream out;
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(DEFAULT_FILE_NAME)));
out.writeObject(studentObj);
out.flush();
System.out.println("here " + studentObj.size());
in.close();
out.close();
} catch (IOException e) {
throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
throw new Exception("CLASS NOT FOUND EXCPETION");
}
【问题讨论】:
-
打印异常的堆栈跟踪:
e.printStackTrace()。这将告诉您遇到的问题。 -
我建议处理数据并保存,例如作为文本文件而不是使用
ObjectOutputStream。您可以进行循环,将数据保存到数组中,然后以一种可以让您再次正确读取它们的方式保存它们。 -
捕获各种异常然后将它们作为基本异常抛出没有真正意义。要么处理这些异常,要么让你的方法抛出那些特定的异常,或者干脆
throws Exception,如果你不在乎它们是什么类型的话。如果您打印异常的堆栈跟踪,那么您将看到问题所在。 -
另外,提示:使用 try-with-resource 块而不是显式关闭流。
-
在这里也包含您的
Student课程可能很有用。
标签: java serialization fileoutputstream