所以我在从对象流中存储或加载散列图时遇到问题。文件已保存,我可以看到它存储了某种信息。问题是,当我尝试读取hashmap时,它会给我一个EOF错误。提前感谢您的帮助。
public synchronized void store(StoredObject storedObject) {
try {
String objectName = storedObject.getObject().getClass().getName();
File file = new File(LOCAL_STORAGE_PATH + objectName);
boolean isNewFile = !file.exists();
output = new ObjectOutputStream(new FileOutputStream(file));
input = new ObjectInputStream(new FileInputStream(file));
if (isNewFile) {
localStorage = new HashMap<String, StoredObject>();
} else {
/////////////////////////
////does not work ///////
/////////////////////////
localStorage = (HashMap) input.readObject();
}
localStorage.put(storedObject.getKey(), storedObject);
output.writeObject(localStorage);;
output.flush();
} catch (IOException ex) {
//Logger.getLogger(LocalServer.class.getName()).log(Level.SEVERE, "ioexception", ex);
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(LocalServer.class.getName()).log(Level.SEVERE, "class missmatch", ex);
}
finally{
try {
output.close();
input.close();
} catch (IOException ex1) {
Logger.getLogger(LocalServer.class.getName()).log(Level.SEVERE, "could not close connection", ex1);
}
}
}
错误消息:
java.io.EOFException的 at java.io.ObjectInputStream $ BlockDataInputStream.peekByte(ObjectInputStream.java:2601) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) at ServiceLayer.LocalServer.LocalServer.store(LocalServer.java:66) 在ServiceLayer.LocalServer.LocalServerTEST.main(LocalServerTEST.java:17)
我试过的东西: 让它同步。对象(StoredObject)和子对象impliments可序列化。
答案 0 :(得分:2)
您将输出和输入代码混合在一起。您正在同时创建输出和输入流。当您致电new FileOutputStream(file)
时,它会替换现有文件,因此当您尝试阅读时,它会为空。
将输出和输入代码移动到两种不同的方法中。