1

I have two methods, one that serialize the Object, and it works ok:

public void record()throws RecordingException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
            outputStream.writeObject(this);
        } catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        }finally
        {
            try
            {
                if (outputStream != null) outputStream.close();
            } catch (IOException ex){}
        }
    }

The problem here when deserializing the object, I get EOFException!:

public final User loadObject(UserType usertype) throws InvalidLoadObjectException
    {
        ObjectInputStream istream = null;
        String path = null;
        if (usertype == UserType.EMPLOYEE)
        {
            path = "data/employee.dat";
        }else if (usertype == UserType.CUSTOMER)
        {
            path = "data/customer.dat";
        }else
            throw new InvalidLoadObjectException("Object is not a sub class of User");

        try 
        {
            istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));             

            User u = loadObject(istream);
            istream.close();
            return u;
        }catch (EOFException ex)
        {
            System.out.println(ex.getMessage());
            return null;
        }catch(Exception ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
    {
        try
        {
            return (User) stream.readObject();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        } catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219

3 Answers3

1

I don't know if this is the cause of your problem, but the code that writes the file has a subtle flaw. In the finally block, you close the stream and ignore any exceptions. If the close() method performs a final flush(), then any exceptions thrown in the flush will go unreported.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Try outputStream.flush() before closing your stream in serialization object.

Istao
  • 7,425
  • 6
  • 32
  • 39
-1

The file was empty, or didn't contain the full serialization of the object.

user207421
  • 305,947
  • 44
  • 307
  • 483