在Java中读取序列化对象时获取EOFEException

在Java中读取序列化对象时获取EOFEException,java,serialization,serializable,eofexception,Java,Serialization,Serializable,Eofexception,我有两种方法,一种是序列化对象,它可以正常工作: public void record()throws RecordingException { ObjectOutputStream outputStream = null; try { outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));

我有两种方法,一种是序列化对象,它可以正常工作:

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){}
        }
    }
这里的问题是当反序列化对象时,我得到了EOFEException!:

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

文件为空,或未包含对象的完整序列化。

请在序列化对象中关闭流之前尝试
outputStream.flush()

我不知道这是否是问题的原因,但写入文件的代码有一个微妙的缺陷。在
finally
块中,关闭流并忽略任何异常。如果
close()
方法执行最终的
flush()
,则在flush中抛出的任何异常都将不被报告。

customer.dat是否包含用户对象?这不会有任何区别。close()调用flush()。请参阅Javadoc。