How to serialize and deserialize an object in Java?

JavaObject Oriented ProgrammingProgramming

The Serialization is a process of changing the state of an object into a byte stream, an object is said to be serializable if its class or parent classes implement either the Serializable or Externalizable interface and the Deserialization is a process of converting the serialized object back into a copy of an object.

During serialization, if we don’t want to write the state of a particular variable in a byte stream using a transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of a variable and stores a default value of that data type i.e. 0 for int, 0 for byte, 0.0 for float, etc. A Serialization of an object can be done through FileOutputStream and ObjectOutputStream class.

Example

import java.io.*;
public class SerializationTest implements Serializable {
   int a = 1, b = 2;
   transient int c = 3;
   public static void main(String[] args) throws Exception {
      SerializationTest obj = new SerializationTest();
      // serialization
      FileOutputStream fos = new FileOutputStream("serialization.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
      // de-serialization
      FileInputStream fis = new FileInputStream("serialization.txt");
      ObjectInputStream ois = new ObjectInputStream(fis);
      SerializationTest test = (SerializationTest)ois.readObject();
      System.out.println("a = " + test.a);
      System.out.println("b = " + test.b);
      System.out.println("c = " + test.c);
   }
}

Output

a = 1
b = 2
c = 0
raja
Published on 05-Sep-2019 13:20:27
Advertisements