Serialization and Deserialization in Java with Example

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.

We have divided the example in 3 classes :

  1. Employee (class whose object is/are to be serialized/deserialized)
  2. Serializze (to serialize the class and store it to a file on local hard drive)
  3. Deserializze (to deserialize the file and fetch values from the object)

Example (Employee.java)

public class Employee implements java.io.Serializable {
	public int id;
	public String name;
	
	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}

Example (Serializze.java)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serializze {

	public static void main(String[] args) {
		Employee object = new Employee(1, "John");
		//String filename = "D:" + File.separator + "java" + File.separator + "file";
		String filename = "D:/java/file";

		// Serialization
		try {
			// Saving of object in a file
			FileOutputStream file = new FileOutputStream(filename);
			ObjectOutputStream out = new ObjectOutputStream(file);

			// Method for serialization of object
			out.writeObject(object);

			out.close();
			file.close();

			System.out.println("Object has been serialized");

		}

		catch (IOException ex) {
			System.out.println("IOException is caught");
		}

	}
}

Example (Deserializze.java)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Deserializze {

	public static void main(String[] args) {

		Employee employee = null;
		String filename = "D:/java/file";

		// Deserialization
		try {
			// Reading the object from a file
			FileInputStream file = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(file);

			// typecasting stream of bytes to employee to deserialize
			employee = (Employee) in.readObject();

			in.close();
			file.close();

			System.out.println("Object has been deserialized ");
			System.out.println("a = " + employee.id);
			System.out.println("b = " + employee.name);
		}

		catch (IOException ex) {
			System.out.println("IOException is caught");
		}

		catch (ClassNotFoundException ex) {
			System.out.println("ClassNotFoundException is caught");
		}
	}

}

Output

after running Serializze class
Object has been serialized
after running Deserializze class
Object has been deserialized

a = 1
b = John

Leave a Reply

Your email address will not be published. Required fields are marked *