Learnitweb

Serialization of multiple objects in same file

Yes, we can serialize multiple objects in a single file. While deserialization the order in which objects are deserialized should be same in which the objects were serialized.

In the following example, we are serializing object of Student, Employee and Car class. While deserialization, the order is same as serialization.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
	String name="John";
}
class Employee implements Serializable{
	int age=23;
}
class Car implements Serializable{
	int wheels=4;
}
class SerializationExample {
	public static void main(String args[]) throws Exception {
        Student student = new Student();
        Employee employee = new Employee();
        Car car = new Car();
        
        System.out.println("Serialization started");
        FileOutputStream fos = new FileOutputStream("test.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(student);
        oos.writeObject(employee);
        oos.writeObject(car);
        System.out.println("Serialization ended");
        
        System.out.println("Deserialization started");
        FileInputStream fis = new FileInputStream("test.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        Student stu = (Student) ois.readObject();
        Employee emp = (Employee) ois.readObject();
        Car c = (Car) ois.readObject();
        
        System.out.println("Deserialization ended");
        
        System.out.println("name: " + stu.name);
        System.out.println("age: " + emp.age);
        System.out.println("c: " + c.wheels);
    }
}

Output

Serialization started
Serialization ended
Deserialization started
Deserialization ended
name: John
age: 23
c: 4

Now try changing the order while deserialization:

Employee emp = (Employee) ois.readObject();
Student stu = (Student) ois.readObject();
Car c = (Car) ois.readObject(); 

We’ll get exception something like this:

Serialization started
Serialization ended
Deserialization started
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to Employee at SerializationExample.main(SerializationExample.java:37)

When you don’t know the order in which objects were serialized

If you don’t know the order of objects then you can use instanceof to check.

Object o=ois.readObject( );
if(o instanceof Student) {
      stu = (Student) o;
} else if(o instanceof Employee) {
      emp = (Employee) o;
} else if(o instanceof Car) {
      c = (Car) o;
}