【问题标题】:eofExeption with objectstream and hashmap对象流和哈希图的 eof 异常
【发布时间】:2014-11-27 17:58:44
【问题描述】:

所以我在从对象流存储或加载哈希图时遇到问题。该文件已保存,我可以看到它存储了某种信息。问题是当我尝试读取哈希图时,它给了我一个 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)和子对象实现可序列化。

【问题讨论】:

    标签: java hashmap objectinputstream objectoutputstream eofexception


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2013-03-21
      • 2019-04-08
      • 2019-02-14
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多