Thursday, June 9, 2016

Serializing objects in java

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.

There are few important things that need to be known.

  • In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.
  • You can also prevent some data in your object from being serialized by marking the attribute as transient.
  • It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
Here is an example of a Java class that can be that can be instantiate as a serializable object.


import java.io.*;


public class Student implements Serializable {
 public String name;
 public String address;
 public transient int regNumber;
 public int classNumber;
 
 public Student(String name,String add,int regNo,int clsNo){
  this.name=name;
  this.address=add;
  this.regNumber=regNo;
  this.classNumber=clsNo;
 }
  public void introduce(){
  System.out.println("Hi!! This is "+name+" and he is from "+address);
 }
 
 public String toString(){
  return name+" - "+address+" - "+regNumber+" - "+classNumber;
 }
}


Here is a example of how to serialize an object and save in a file

import java.io.*;

public class Serializer {

 public static void main(String args[]){
  
  Student stdnt = new Student("Jhon","111 street,george town",1234,8);
  try{
   String path = "/home/iiii/store/student.ser";
   FileOutputStream fo = new FileOutputStream(path);
   ObjectOutputStream oo=new ObjectOutputStream(fo);
   oo.writeObject(stdnt);
   oo.close();
   fo.close();
   System.out.println("Object is serialized and saved in "+path);
  }catch(IOException e){
   e.printStackTrace();
  }  
 }
}


Here is a example of how to deserialize what is saved in the file in to an object.

import java.io.*;

public class Deserializer {
 
 public static void main(String args[]){
  String path = "/home/iiii/store/student.ser";
  Student s = null;
  try{
   FileInputStream fi = new FileInputStream(path);
   ObjectInputStream oi = new ObjectInputStream(fi);
   s=(Student) oi.readObject();
   oi.close();
   fi.close();
  }catch(IOException e){
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
  
  System.out.println(s);  
 }
}


No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...