serialization - java.io.EOFException when reading an object through ObjectInputStream -


wrote simple piece of code top serialize standard employee object , deserialize in the same machine different class. both programs compiled , executed obj output stream create serialized object.

problem deserializing it. program when run gives eof exception. here code using:

serialize-

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

deserialize -

   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 " + emp); //system.out.println("obj props "+ emp.name);  } catch(exception e){      e.printstacktrace(); }  }  } 

this printstacktrace:

inside main inside try streams initialized java.io.eofexception @ java.io.objectinputstream$blockdatainputstream.peekbyte(objectinputstream.java:2598) @ java.io.objectinputstream.readobject0(objectinputstream.java:1318) @ java.io.objectinputstream.readobject(objectinputstream.java:370) @ oistreamdemo.main(oistreamdemo.java:16) 

thank you.

you did not write employee object objectoutputstrem therefore add

oout.writeobject(e); 

Comments