java - eofException 与 objectstream 和 hashmap

标签 java hashmap objectinputstream objectoutputstream eofexception

所以我在从对象流存储或加载 HashMap 时遇到问题。文件已保存,我可以看到它存储了某种信息。问题是当我尝试读取 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 在 java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601) 在 java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) 在 java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) 在ServiceLayer.LocalServer.LocalServer.store(LocalServer.java:66) 在ServiceLayer.LocalServer.LocalServerTEST.main(LocalServerTEST.java:17)

我尝试过的东西: 使其同步。对象(StoredObject)和子对象实现了可序列化。

最佳答案

您的输出和输入代码混合在一起。您同时创建输出和输入流。当您调用new FileOutputStream(file)时,它会替换现有文件,因此当您尝试读取它时,它是空的。

将输出和输入代码移动到两种不同的方法中。

关于java - eofException 与 objectstream 和 hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27176598/

相关文章:

Java + 列表到 HashMap

c - 哈希索引与数组大小有何关系?

java - 将 PrintWriter 与字节流一起使用

Java 程序流程和 OOP

java - 如何停止按下背面的媒体播放器,无论它是否正在播放?

java - 您的产品中应该包含哪个版本的 jdbc4 postgres 驱动程序?

firebase - 如何使用flutter中的Map在Firestore中动态添加特定集合的文档的字段?

Java:尝试使用 objectoutputstream/objectinputstream 读取对象 - 崩溃

java - 不使用 while(true) 从文件反序列化多个对象

java - Spring Cloud Dataflow 设置系统属性