Hi All,

So today we gonna discuss about Serialization of Objects in Java. Well, to wrap up the whole concept in a single statement – “Serialization is a way to convert an object into stream of bits that can saved into a file. Then we can reconstruct (deserialize) the object from that file having those stream of bits.”.

So ultimately, it is a massive concept in terms of functionality it provides and level of problems it can solve. Take a simple example. We can save an object into a file where an object is containing lot of information. Then we can transfer this file over internet to anywhere and the other person can deserialize the object from that file and can use it. So that means, the other person can get all the data that was created by first user from that deserialized object.

Let’s have a look at the following simple example.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class MainClass implements Serializable {
	public static void main(String args[])
	{
		MainClass object = new MainClass();
		String[] list = new String[]
		{
			"Value1", "Value2", "Value3"	
		};
		object.serializeObject(list);
		String[] deserializedList = object.deserializeObject();
		for(String value : deserializedList)
		{
			System.out.println(value);
		}
	}

	private String[] deserializeObject() {
		String[] list = null;
		try {
			FileInputStream fileInputStream = new FileInputStream("file.txt");
			ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
			list = (String[])objectInputStream.readObject();
			objectInputStream.close();
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	private void serializeObject(String[] list) {
		try {
			FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(list);
			objectOutputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

 

In the above shown program, we can see that I’ve written an object into a file which is further again used by reading the object from the same file. That means, we can save an object into the file (which is actually mirroring the object into a file using stream of bytes) and we can also read that object which will retrieve it’s data too.

Keeping the complexity apart, my main motive was to discuss the concept of Serialization.

Thank you!

Advertisements