java.io.EOFException 通过 ObjectInputStream 读取对象时

java.io.EOFException when reading an object through ObjectInputStream

写了一段简单的代码,顶部序列化标准员工对象,并在同一台机器上从不同 class 反序列化它。两个程序都编译并执行了 Obj 输出流以创建序列化对象。

问题出在反序列化上。当 运行 给出 EOF 异常时的程序。 这是我使用的代码:

序列化-

    import java.io.*;
public class OOStreamDemo{

public static void main(String []a){

Employee e = new Employee("Abhishek Yadav", 'i', 10014);
FileOutputStream fout = null;
ObjectOutputStream oout = null;
try{
fout = new FileOutputStream("emp.ser");
oout = new ObjectOutputStream(fout);

} catch(Exception ex1){
System.out.println(oout);
    ex1.printStackTrace();

}


finally{

try{
oout.flush();
oout.close();
fout.close();
} catch(IOException ex2){
    ex2.printStackTrace();

}
}
}
}

反序列化 -

   import java.io.*;
public class OIStreamDemo{
public static void main(String []a){

System.out.println("Inside main");

FileInputStream fin = null;
ObjectInputStream oin = null;
Employee emp;

try{
System.out.println("Inside try");
fin = new FileInputStream("emp.ser");
oin = new ObjectInputStream(fin);
System.out.println("Streams Initialized");
while((emp = (Employee)oin.readObject()) != null)
    {

System.out.println(emp.toString());
    }
System.out.println("Object read");
//System.out.println("Read object is " + emp);
//System.out.println("Obj props are "+ emp.name);

} catch(Exception e){

    e.printStackTrace();
}

}

}

这是 printStackTrace:

Inside main
Inside try Streams
Initialized
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2598)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1318)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at OIStreamDemo.main(OIStreamDemo.java:16)

谢谢。

您没有将 Employee 对象写入 ObjectOutputStrem 因此添加

oout.writeObject(e);