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

时间:2010-11-30 05:36:07

标签: java serialization serializable eofexception

我有两个方法,一个序列化Object,它可以正常工作:

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

反序列化对象时的问题,我得到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);
        }
    }

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

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

答案 2 :(得分:-1)

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