eofExeption with objectstream and hashmap

208 views Asked by At

so i have a problem with storing or loading a hashmap from an objectstream. The file is saved and i can see that it store some kind of information. the problem is when i try to read the hashmap it gives me an EOF error. thanks in advance for your help.

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);
        }
    }

}

the error message:

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) at ServiceLayer.LocalServer.LocalServerTEST.main(LocalServerTEST.java:17)

stuff i have tried: make it syncronized. The object(StoredObject) and subobjects impliments serializable.

1

There are 1 answers

0
Boann On

You have your output and input code mixed together. You're creating the output and input streams at the same time. When you call new FileOutputStream(file), it replaces the existing file, so when you try to read it, it's empty.

Move your output and input code into two different methods.