I wrote 2 objects to a file but when I try to read back the objects written it throws an exception in the desrialize method. It works fine when I write a single object but fails with 2 objects written to the file and the exception is thrown while reading the second object.
File_obj.Serialize_object(d, "/home/dasman/doc/serobj1.bin");
File_obj.Serialize_object(b, "/home/dasman/doc/serobj1.bin");
File_obj.deSerialize_object("/home/dasman/doc/serobj1.bin");
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1373)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
at Testpackage.File_obj.deSerialize_object(File_obj.java:242)
at File_test.main(File_test.java:28)
The method for serialize and deserialize in File_obj class are here
public static void Serialize_object(Object obj,String filename){
File a = new File(filename);
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(a,true)));
}catch(IOException e){
e.printStackTrace();
}
try{
out.writeObject(obj);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void deSerialize_object(String filename){
File a = new File(filename);
int objcount = 0;
ObjectInputStream in = null;
try{
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(a)));
}catch(IOException e){
e.printStackTrace();
}
Serializable_test obj1 = null;
try{
while(true){
obj1 = (Serializable_test) in.readObject();
objcount++;
System.out.println("The object area is :" + obj1.get_area());
}
}catch(EOFException e){
System.out.println("END of object files reached objects read :" + objcount);
//in.close();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}