Serialization In Java

Introduction 

 
Serialization is a way to you save the specific state of the program in a file so that you can retrieve that file in the class at some other point. A class implements the Serializable interface to perform serialization.
  

Creating the serialized file

 
Use the following procedure to create the serialized file:
  1. Create a FileOutputStream object. A FileOutputStream object knows how to connect to a file that is already created or it creates the file and then connects with it. It is a connection stream that writes bytes to the file. 
     
    FileOutputStream fos=new FileOutputStream("MyFile.ser");
     
  2. Now create an ObjectOutputStream Object. An ObjectOutputStream object allows you to write the Object, but it cannot directly write to the file. So we use a FileOutputStream object to write the object to the file. ObjectOutputStream is a chain stream that converts the object into data that can be written into streams.
     
    ObjectOutputStream oos=new ObjectOutputStream(fos);
     
  3. Now we write the object in the file using the writeObject() method of the ObjectOutputStream object. 
     
    oos.writeObject(object reference); 
     
  4. Now close the objectoutputstream object using the close() method. Closing the stream at the top will close the one underneath it, so FileOutputStream automatically closes.
      
    oos.close();
A diagrammatic representation of the preceding process is: 
image1.gif
 
 
An example of how to create a serialized file is: 
  1. import java.io.FileNotFoundException;    
  2. import java.io.FileOutputStream;    
  3. import java.io.IOException;    
  4. import java.io.ObjectOutputStream;    
  5. import java.io.Serializable;     
  6. public class SerializableExample implements Serializable {    
  7.        int x;    
  8.        int y;            
  9.      /**  
  10.        *@param args  
  11.        */    
  12.       public static void main(String[] args) {    
  13.            // TODO Auto-generated method stub    
  14.             SerializableExample se=new SerializableExample();    
  15.             se.x=3;    
  16.             se.y=4;    
  17.            try {    
  18.                   FileOutputStream fos=new FileOutputStream("File.ser");    
  19.                   ObjectOutputStream oos=new ObjectOutputStream(fos);    
  20.                   oos.writeObject(se);    
  21.                   oos.close();    
  22.                   System.out.println("File is created");                                       
  23.             }catch (FileNotFoundException e) {    
  24.                  // TODO Auto-generated catch block    
  25.                   e.printStackTrace();    
  26.             }catch (IOException e) {    
  27.                  // TODO Auto-generated catch block    
  28.                   e.printStackTrace();    
  29.             }    
  30.       }    
  31. }    
A file with the name File.ser will be created in the folder in which you have created your class. This file.ser can be used in another part of the class and you can get the object and its state by deserializing the file. 
 

Deserializing a file

 
Use the following procedure to deserialize a file:
  1. Create a FileInputStream Object. A FileInputStream Object creates a connection with the file that is to be deserialized. If the file does not exist then it gives the exception FileNotFound. 
     
    FileInputStream fis=new FileInputStream("File.ser"); 
     
  2. Create a ObjectInputStream object. A ObjectInputStream object transfers the bytes from the file into objects. 
     
    ObjectInputStream ois=new ObjectInputStream(fis);
      
  3. Now we use the ObjectInputStream readObject() method to get the objects. Since the method returns the object as an Object type, we downcast it to our class name. 
     
    Classname reference=(Classname)ois.readObject();
      
  4. Now close the ObjectInputStream using the close() method. Since the ObjectInputStream is a high level stream, closing it means all the streams, like FileInputStream, are automatically closed. 
     
    ois.close();
A diagrammatic representation of the above process is:
 
 
image2.gif
 
 
The code to deserialize the file that we serialized above is:
  1. try {    
  2.      FileInputStream fis = new FileInputStream("File.ser");    
  3.      ObjectInputStream ois=new ObjectInputStream(fis);    
  4.      SerializableExample se1=(SerializableExample)ois.readObject();    
  5.      System.out.println(se1.x);    
  6.      System.out.println(se1.y);    
  7. }catch (FileNotFoundException e) {    
  8.      // TODO Auto-generated catch block    
  9.       e.printStackTrace();    
  10. }catch (IOException e) {    
  11.     // TODO Auto-generated catch block    
  12.     e.printStackTrace();    
  13. }   
The output will be the value of the instance variable of the object that was serialized. So, the output will be 3 and 4. 
 
I hope this article was useful to you and thanks for reading it.