【问题标题】:java.io.EOFException when reading an object through ObjectInputStream通过 ObjectInputStream 读取对象时出现 java.io.EOFException
【发布时间】:2016-04-30 22:27:58
【问题描述】:

编写了一段简单的代码,顶部序列化标准员工对象,并在同一台机器上的不同类中反序列化它。两个程序都编译并执行 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)

谢谢。

【问题讨论】:

    标签: java serialization eofexception


    【解决方案1】:

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

    oout.writeObject(e);
    

    【讨论】:

    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多