0

所以我在从对象流存储或加载哈希图时遇到问题。该文件已保存,我可以看到它存储了某种信息。问题是当我尝试读取哈希图时,它给了我一个 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.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2601) 的 java.io.EOFException 在 java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) 在 java.io.ObjectInputStream.readObject(ObjectInputStream.java:第371章)

我试过的东西:让它同步。对象(StoredObject)和子对象实现可序列化。

4

1 回答 1

2

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

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

于 2014-11-27T18:04:12.497 回答