为什么在反序列化保存的对象时会出现EOF异常

时间:2015-09-13 21:13:15

标签: java serialization deserialization

我正在尝试序列化然后反序列化多个对象。我可以毫无问题地写入文件,但在选择deserialize选项时,我得到以下堆栈跟踪。以前我可以成功地序列化和反序列化一个对象。

dos中的堆栈跟踪是:

java.io.EOFException
        at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Sourc
e)
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at mainmenutest.DeserializeDemo.Deserialize(DeserializeDemo.java:23)
        at mainmenutest.MainmenuTest.getInput(MainmenuTest.java:64)
        at mainmenutest.MainmenuTest.main(MainmenuTest.java:26)

我的反序列化代码如下:

package mainmenutest;

/**
 *
 * @author Darren Estcourt
 */
import java.io.*;
public class DeserializeDemo
{
   public void Deserialize()
   {
      ClubInfo club = null;
      ClubInfo club2 = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("C:/tmp/club.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         club = (ClubInfo) in.readObject();
         club2 = (ClubInfo) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Club class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Saved game loaded...");
      System.out.println("Name: " + club.teamName);
      System.out.println("Stadium: " + club.stadium);
      System.out.println("Division: " + club.division);
     // System.out.println("SSN: " + club.SSN);
      System.out.println("Stadium Capacity: " + club.stadiumCapacity);
      System.out.println("Name : " + club2.teamName);

    }
}

我不希望有人为我修理它,只是指向正确的方向。我计划最终反序列化大约20个对象。

1 个答案:

答案 0 :(得分:1)

当没有更多的对象要读取时,或者由于某些其他原因意外地流到达终点时,会抛出

EOFException(零长度,它被截断,关闭时没有正确刷新)

在这种情况下,readObject()引发了异常,因此只有第一个适用。看起来你要么序列化没有对象并试图读取一个对象,要么序列化一个对象并试图读取两个。