Learnitweb

Serialization and Deserialization example

In the following example, we are serializing instance of Student class. Student class has two fields, rollNo and age. We are saving state of the object in test.ser file. ObjectOutputStream class has method writeObject to write object state and ObjectInputStream class has method readObject to read object state.
During serialization we are reading state of object from test.ser file and printing details on console.

import java.io.*;

class Student implements Serializable {
	int rollNo = 100;
	int age = 25;
}

class SerializationExample {
	public static void main(String args[]) throws Exception {
		Student d1 = new Student();
		
		System.out.println("Serialization started");
		FileOutputStream fos = new FileOutputStream("test.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(d1);
		System.out.println("Serialization ended");
		
		System.out.println("Deserialization started");
		FileInputStream fis = new FileInputStream("test.ser");
		ObjectInputStream ois = new ObjectInputStream(fis);
		Student d2 = (Student) ois.readObject();
		System.out.println("Deserialization ended");
		
		System.out.println("rollNo: " + d2.rollNo);
		System.out.println("age: " + d2.age);
	}
}

Output

Serialization started
Serialization ended
Deserialization started
Deserialization ended
rollNo: 100
age: 25