serialization

PREVIOUS

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implementsjava.io.Serializable interface by default.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface

Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability.
It must be implemented by the class whose object you want to persist. Let's see the example given below:
  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  public Student(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }  

ObjectOutputStream class

An ObjectOutputStream is used to write primitive data types and Java objects to an OutputStream.Only objects that support the java.io.Serializable interface can be written to streams.

Constructor

1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that writes to the specified OutputStream.

Example of Java Serialization

In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.
  1. import java.io.*;  
  2. class Persist{  
  3.  public static void main(String args[])throws Exception{  
  4.   Student s1 =new Student(211,"ravi");  
  5.   
  6.   FileOutputStream fout=new FileOutputStream("f.txt");  
  7.   ObjectOutputStream out=new ObjectOutputStream(fout);  
  8.   
  9.   out.writeObject(s1);  
  10.   out.flush();  
  11.   System.out.println("success");  
  12.  }  
  13. }  
success

Deserilization in java

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws IOException {}creates an ObjectInputStream that reads from the specified InputStream.

Example of Java Deserialization

  1. import java.io.*;  
  2. class Depersist{  
  3.  public static void main(String args[])throws Exception{  
  4.     
  5.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
  6.   Student s=(Student)in.readObject();  
  7.   System.out.println(s.id+" "+s.name);  
  8.   
  9.   in.close();  
  10.  }  
  11. }  
211 ravi

No comments:

Post a Comment