簡體   English   中英

在Java中讀取序列化對象時獲取EOFException

[英]Get EOFException while reading serialized object in Java

我有兩種方法,一種將對象序列化,並且可以正常工作:

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

我不知道這是否是導致您出現問題的原因,但是寫入文件的代碼有一個細微的缺陷。 finally塊中,關閉流並忽略任何異常 如果close()方法執行最終的flush() ,則刷新中拋出的任何異常都將不會報告。

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

在序列化對象中關閉流之前,請嘗試使用outputStream.flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM