Read An Object From File In Java (Deserialization)

SHARE & COMMENT :

In my previous tutorial I have explained about writing an object to a file using the serialization concept. Once you have written to a file, that file will be transferred across the network and would reach the destination. Once it is received, the receiver has to decode that file abd reading and converting back to the original object. This process is known as Deserialization in Java. I have extend the previous example to deserialize the same object back to the original. Lets look at the example.

DeserializationExample.java

package javabeat.net.core;

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

public class DeserializationExample {
	public static void main(String args[]) {

		DeserializationExample deserializer = new DeserializationExample();
		Employee employee = deserializer.deserialzeEmployee();
		System.out.println(employee);
		System.out.println("Deserialization Done");
	}

	public Employee deserialzeEmployee() {

		Employee employee;

		try {

			FileInputStream filein = new FileInputStream("employee.ser");
			ObjectInputStream objis = new ObjectInputStream(filein);
			employee = (Employee) objis.readObject();
			objis.close();

			return employee;

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
}

Output…

Name : Krishna, ID : India
Deserialization Done

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better