This discussion is archived
5 Replies Latest reply: Jan 30, 2013 3:06 AM by EJP RSS

Serialization and Deserialization of multiple objects from single file

987960 Newbie
Currently Being Moderated
I have certain images and those images are coming periodically.
I want to serialize all images one by one in a flat file.
Please refer the following algorithm

While(true) {
Read the configured path and collect all images.
For(image 1 to n){
Prepare the serialize object
Open the flat file in append mode and write that serialize object
Move that file to the success folder.
Sleep for some time
}
}
After then I need to de-serialize all those objects written into that file.

I am getting error while de-serialize all those objects.

Please refer the following code for serialization.

public void writeObjects(ImageDetails objSer) throws Exception {

          FileOutputStream fileOut = new FileOutputStream("D:\\Serialization\\image.ser", true);
          ObjectOutputStream out = new ObjectOutputStream(fileOut);
          try{
               out.writeObject(objSer);
          }catch(Exception e){
               System.out.println(e);
          }
          out.reset();
          out.flush();
          out.close();
          fileOut.close();
          objSer = null;
     }

Please refer the following code for de-serialization

public void readObjects(String filePath) throws IOException {
          FileInputStream fis = null;
          ObjectInputStream ois = null;
          ImageDetails imageDetails = null;
          try {
               fis = new FileInputStream(filePath);
               ois = new ObjectInputStream(fis);
               
               while((imageDetails = (ImageDetails) ois.readObject()) != null){
                    System.out.println("=======Start========");
                    System.out.println(imageDetails.getImageData());
                    System.out.println(imageDetails.getTripName());
                    System.out.println(imageDetails.getImageName());
                    System.out.println("=======End==========");
                    imageDetails = null;
               }
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               fis.close();
               ois.close();
               
          }

     }
I am getting this error while de-serializing(after serializing two objects in the flat file).
=======Start========
D:\Serialization\14.jpg
Test-2
14.jpg
=======End==========
java.io.StreamCorruptedException: invalid type code: AC
     at java.io.ObjectInputStream.readObject0(Unknown Source)
     at java.io.ObjectInputStream.readObject(Unknown Source)
     at FileWrite.readObjects(FileWrite.java:50)
     at FileWrite.main(FileWrite.java:17)
Please help me for the same. I do not want to put all those images into a collection as after some time I will get another list of files and those files also needs to be seriliaze.