Serialization Program in Java


Last we seen that Serialization & Deserialization.

Serialization is saving state of object to file. internally process of converting object from java support form to file support form either network support form know as serialization.

Deserialization is reading state from file and store into object. internally process of converting file support form to java support form.
Lest we check in programming.


I create java file name and save demoserialization.java. contain two class myclass and demoserialization in main method which we have to execute. in myclass contain just two string variable fname and lname. and you must have to implements Serializable interface for serialization process. ok Lest check...

ex. demoserialization,java File

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; class myclass implements Serializable{
          public String fname;
          public String lname;
}
 public class demoserialization { public static void main(String args[]){
myclass obj = new myclass();
              obj.fname= "XYZ";
              obj.lname= "ABC";
              try{
//First,Need to saving state of object into file so you must need to write file path and file name.   

FileOutputStream fos = new FileOutputStream("D:myclassfile.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);//Need fos object to write.

oos.writeObject(obj);//write state of object to file.
oos.close();//close objectoutputstream
           fos.close();//close fileoutputstream
           System.out.println("Save state from object to File : myclassfile.txt");
}
         catch(Exception e){
         }
}
}
--------------------------------------------------------------------------

now we check process of deserialization in programing.

ex. deserialization.java

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

class deserialization{
          public static void main(String args[]){
// you no deed to create instance of class. so myclass objd is null.
         myclass objd = null;
         try{
         FileInputStream fis = new FileInputStream("D:myclassfile.txt");
         ObjectInputStream ois = new ObjectInputStream(fis);
//read state data from file and type casting to myclass form mean java support form..                
         objd = (myclass) ois.readObject();
         ois.close();
         fis.close();
        }catch(Exception e){
        }                
//print your object state....
System.out.println("fname -> "+objd.fname);
System.out.println("Lname -> "+objd.lname);  
   }
}

it's just simple program to understand serialization and de-serialization.


Comments