Core Java Tutorial

Core Java Tutorial

Serialization and De-serialization in java

Serialization

Serialization is the process of converting Object state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

De-serialization 

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Example

Employee.java

import java.io.*;


class Employee implements Serializable

{

 int id = 1;

 String name = "No Name";

}

 

Serialization of java object

 

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;


public class SeralizeExample {


 public static void main(String[] args) throws IOException {

  Employee e = new Employee();

  e.id = 4;

  e.name = "candidjava";


  FileOutputStream fo = new FileOutputStream("sam.ser");

  ObjectOutputStream oo = new ObjectOutputStream(fo);

  oo.writeObject(e);


  System.out.println("sucess");

  oo.close();

 }

}
Run the above program to serialize a object

De-serialization java object

 

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class DeserializeObject

{

 public static void main(String[] args) throws Exception

 {


  FileInputStream fis = new FileInputStream("sam.ser");

  ObjectInputStream ois = new ObjectInputStream(fis);


  Employee e = (Employee) ois.readObject();


  System.out.println(e.name + " " + e.id);

  ois.close();


 }

}

Run the above program to deserialize a object