What is Serialization in JAVA - Example ?

Posted By: Unknown - 10:51 AM
Java provides serialization API that gives you a facility to convert objects into sequence of bytes and write into them in a file (Serialization). Same objects can be returned back from the same file (De-serialization).


Why we need it,
Some time we need objects for a long time. Even after the execution of the program (for reuse etc). Raw data can be written in a text file but objets? Serialization API gives you a flexibility to convert objects into sequence of bytes and write them in a file, which can be used later.

In other words "Its a file writing of objects"

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

for example-
When the program is done executing, a file named mydata.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Hitesh";
      e.address = "Bangalore";
      e.ID = 111;
      e.mobilenumber = 9123456789;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("mydata.ser");
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
          fileOut.close();
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Now the following deserialization process can give you the data back-

import java.io.*;
   public class DeserializeDemo
   {
      public static void main(String [] args)
      {
         Employee e = null;
         try
         {
            FileInputStream fileIn =
                          new FileInputStream("mydata.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        }catch(IOException i)
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)
        {
            System.out.println(.Employee class not found.);
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Data...");
        System.out.println("Name: " + e.name);
        System.out.println("Address: " + e.address);
        System.out.println("ID: " + e.ID);
        System.out.println("Mobile Number: " + e.mobilenumber);
    }
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.