【问题标题】:Get EOFException while reading serialized object in Java在 Java 中读取序列化对象时获取 EOFException
【发布时间】:2011-05-17 16:28:07
【问题描述】:

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

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

【问题讨论】:

  • customer.dat 是否包含用户对象?

标签: java serialization serializable eofexception


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这不会有任何区别。 close() 调用flush()。请参阅 Javadoc。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      相关资源
      最近更新 更多