Wrote a simple piece of code top serialize standard employee object and deserialize it in the the same machine from different class. Both programs compiled and executed Obj output stream to create serialized object.
Problem is with deserializing it. Program when run gives EOF exception. Here is the code I am 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 is " + emp);
//System.out.println("Obj props are "+ emp.name);
} catch(Exception e){
e.printStackTrace();
}
}
}
This is the 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)
Thank You.
You did not write the Employee
object to the ObjectOutputStrem
therefore add
oout.writeObject(e);