1

オブジェクトをシリアル化する 2 つのメソッドがあり、正常に動作します。

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 に答える