Powered by Blogger.

What is Deserialization in java ? Write a simple program using Deserialization?

>> Monday, April 18, 2011

Deserialization is a process of converting the data from files or database converting to Stream of bytes using class Objects.


The Deserialization can be done after serializing the data only.Then we can read the data from the serialized files.

Convert your Serialized file into file form.

File fromFile = new File("Emp.ser");

By using the below two classes we can do the process of deserialization.
#1. FileInputStream
#2. ObjectInputStream
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.
FileInputStream fis = new FileInputStream(fromFile);

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This can be Converts the Serialized file into the Object form.
ObjectInputStream ois = new ObjectInputStream(fis);

To get the object of a serialized file we have to typecast into our class Employee to read the values in a file using variable names.
Employee emp = (Employee) ois.readObject();

After that close all the object connections.
You should write the  Employee class already written in Serialization.(check it there) 
Program for Deserialization:
package javabynataraj.iopack;

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

public class Deserial {
    public static void main(String arg[]) {
        File fromFile = new File("Emp.ser");
        try {
            FileInputStream fis = new FileInputStream(fromFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Employee emp = (Employee) ois.readObject();
            System.out.println("Deserialized data: \n"+ emp.eno + " "+ emp.ename +" "+ emp.esal+" "+emp.eaddr+ "  from Emp.ser");
            ois.close();
        } catch(IOException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        } catch(ClassNotFoundException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        }
    }
}

Related Posts Plugin for WordPress, Blogger...

About Author

My Photo
GeekDude
Hi, this is Muralidhar from Chennai.I like blogging on some known things. Trying to provide some basic information for java beginners.
View my complete profile

Random Posts

© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.