Friday 25 October 2013

serialization , deserialization in java example


Serialization is the process of translating object state into a format that can be stored in a file , memory buffer, or transmitted across a network connection .
This process of serializing an object is also called marshalling an object.Opposite extracting a data structure from a series of bytes, is deserialization known as unmarshalling. Mainly you see in Hibernate , Jpa etc. We can serialize our Model classes using Serializable interface.


Here we have create a Simple Java bean class Employee and its variables having some values. We can save this object into a file or into a database table.
i m saving these object into a file :-


Employee.java
package com.javastoreroom.thread;

import java.io.Serializable;

public class Employee  implements Serializable{     // serialization interface has no methods , fields and serves only to identify the semantics
                                                    // of being serializable. 
 /**
  * 
  */
 private static final long serialVersionUID = 1L; //JVM use this value to assign this version serialized objects
 
 
 private String userName;
 private String section;
 private String rollNumber;
 
 
 public Employee(String name , String section , String number){
  
  this.userName = name;
  this.section =  section;
  this.rollNumber = number;
 }
 

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getSection() {
  return section;
 }

 public void setSection(String section) {
  this.section = section;
 }

 public String getRollNumber() {
  return rollNumber;
 }

 public void setRollNumber(String rollNumber) {
  this.rollNumber = rollNumber;
 }

}


ObjectOutputStream Class writes primitive data types and Java objects to an OutputStream. The objects can be read using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream.objects that support the java.io.Serializable interface can be written to streams.

writeObject method is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream.ObjectOutputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are written using writeObject method.

public final void writeObject(Object obj)throws IOException


ObjectInputStream Class deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectInputStream is used to recover those objects previously serialized.

readObject is used to read an object from the stream.
public final Object readObject() throws IOException,ClassNotFoundException
ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read.


SerilazationDeserlization.java

package com.javastoreroom.thread;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerilazationDeserlization {

 public static void main(String[] args) {
  serializeObject();
  deserializeObject();
 }

 private static void serializeObject() {
  Employee employee = new Employee("Arun", "A", "8095");
  FileOutputStream fileOutputStream = null;
  ObjectOutputStream objectOutputStream = null;
  try {
   fileOutputStream = new FileOutputStream("Arun.txt");
   objectOutputStream = new ObjectOutputStream(fileOutputStream);
   objectOutputStream.writeObject(employee);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    objectOutputStream.flush();
    objectOutputStream.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 private static void deserializeObject() {
  FileInputStream fileInputStream;
  try {
   fileInputStream = new FileInputStream("Arun.txt");
   ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
   Employee employee2 = (Employee) inputStream.readObject();
   System.out.println(employee2.getUserName());
   System.out.println(employee2.getRollNumber());
   System.out.println(employee2.getSection());
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }

 }

}



when execute above code arun.txt created contain serialize object :-
¨Ì  sr !com.javastoreroom.thread.Employee           L 
rollNumbert  Ljava/lang/String;L  sectionq ~  L  userNameq ~  xpt  8095t  At  Arun 

when you deserialize arun.txt you will get following output :-
Arun
8095
A

Done :)

No comments:

Post a Comment