Object Serialization is a simple way to store the state of an object into a byte stream. This stream can be stored in a file. The reverse is called Object De-Serialization, which is restoring the object to its state by reading the serialized stream. Java provides inbuilt implementation to serialize & de-serialize the object via ObjectOutputStream and ObjectInputStream classes. However for more control over how the object serializes custom serializers can be implemented.

Serialize Object to File

The following snippet shows how to Serialize an object to a file stream and then how to de-serialize the stream and reconstruct the object with the same state.

package com.livrona.snippets.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * This snippet shows how to write the object to a file (serialize) and read it
 * back (de-serialize).
 * 
 * @author mvohra
 * 
 */
public class ObjectSerializer {

	// file where serialized object would be stored
	private static final String OBJECT_FILE_NAME = "object.dat";

	/**
	 * De-serialize the Object from the file
	 */
	public Object deserialize(String fileName) {

		Object deserializedObject = null;
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(
					fileName));
			deserializedObject = in.readObject();
			in.close();
			System.out.println("Object : " + deserializedObject.getClass()
					+ " de-serialized successfully");
		} catch (Exception ex) {
			System.out.println("Error Reading Object to File :"
					+ ex.getMessage());
			ex.printStackTrace();

		}

		return deserializedObject;

	}

	/**
	 * Serializes the object to a file
	 * 
	 * @param objToSerialize
	 */
	public void serialize(Object objToSerialize,String fileName) {

		try {
			ObjectOutputStream out = new ObjectOutputStream(
					new FileOutputStream(fileName));
			out.writeObject(objToSerialize);
			out.close();
			System.out.println("Object : " + objToSerialize.getClass()
					+ " serialized successfully");
		} catch (Exception ex) {
			System.out.println("Error Saving Object to File :"
					+ ex.getMessage());
			ex.printStackTrace();
		}
	}

	/**
	 * main(args[]) method
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		// Example Object to serialize,it could an instance of any class.
		// the following is an ArrayList objects to String with 3 values namely
		// A,B,C
		ArrayList<String> list = new ArrayList<String>();
		list.add("A");
		list.add("B");
		list.add("C");

		// create the helper class instance to serialize/de-serialize object
		ObjectSerializer os = new ObjectSerializer();
		// invoke it
		os.serialize((Object) list,OBJECT_FILE_NAME);

		// read back the serialized object
		Object desrializedObject = os.deserialize(OBJECT_FILE_NAME);
		// type cast back as list
		ArrayList<String> deserializedList = (ArrayList<String>) desrializedObject;

		// print the deserializedList to see if we have all data back
		for (String listItem : deserializedList) {
			System.out.println(listItem);
		}

	}
}