Java Serialization: Class 4

In Serialization, we write and read Object from .ser file. So, we now discuss on the property of .ser file. How we can read and write multiple Objects in a .ser file.

Order of saving objects in .ser file:
We can serialize any number of Objects to the File, But in which order we serialized in the same order only we have to De-serialize. That is, in the Serialization the order of Objects is important.

If we try to deserialize in different order, then we will get classtypeexception.
Dog d1 = new Dog();
Cat c1 = new Cat();
Rat r1 = new Rat();
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d1);
oos.writeObject(c1);
oos.writeObject(r1);

//Now read Object in same order

FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Dog d2 = (Dog)ois.readObject();
cat c2 = (Cat)ois.readObject();
Rat r2 = (Rat)ois.readObject();

If we do not know order of Object Serialization, then do mention below:
FileInputStream fis = new FileInputStream("xyz.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
if(o instanceof Dog){  //checking either the Object is of Dog class
 Dog d2 = (Dog)o;
 //perform Dog specific functionality
}
else if(o instanceOf Cat){
 Cat c2 = (Cat)o;
 //perform cat specific functionality
}

Conclusion:
The sequence in which we write Object in .ser file, in the same sequence we need to read Object Otherwise we will get classtypeexception. If we do not know the sequence then use instanceOf to check the Object instance.

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment