Java - Serialize custom object with serialVersionUID

Description

Serialize custom object with serialVersionUID

Demo

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class Main {

  public static void main(String[] args) {

    Employee object1 = new Employee(1, "amy");
    Employee object2 = new Employee(2, "ankit");

    try {/*w  w  w .ja  va2 s .com*/
      OutputStream fout = new FileOutputStream("ser.txt");
      ObjectOutput oout = new ObjectOutputStream(fout);
      System.out.println("Serialization process has started, serializing employee objects...");
      oout.writeObject(object1);
      oout.writeObject(object2);
      fout.close();
      oout.close();
      System.out.println("Object Serialization completed.");

    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

}

class Employee implements Serializable {
  private static final long serialVersionUID = 1L;
  private Integer id;
  private String name;
  private String addedField;

  public Employee(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", name=" + name + "]";
  }

}

Deserialization

Demo

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;

public class _02Deserialization {
  public static void main(String[] args) {
    try {// w  w w  .j  a  v a2 s . c  om
      InputStream fin = new FileInputStream("ser.txt");
      ObjectInput oin = new ObjectInputStream(fin);

      System.out.println("DeSerialization process has started, displaying employee objects...");
      Employee emp;
      while ((emp = (Employee) oin.readObject()) != null) {
        System.out.println(emp);
      }
      fin.close();
      oin.close();

    } catch (IOException | ClassNotFoundException e) {
      e.printStackTrace();
    }

    System.out.println("Object deSerialization completed.");

  }
}

Related Topic