1

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

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

3 回答 3

1

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

于 2010-11-30T07:59:30.533 回答
0

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

于 2010-11-30T07:19:58.073 回答
-1

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

于 2010-11-30T05:48:21.573 回答