Understanding of serialization in J2SE

Time:2021-12-26

Java embodies a simple programming style everywhere. Serialization, as one of the most commonly used functions, is particularly “simple” in Java. With the help of objectinputstream and objectoutputstream, we can easily implement serialization.

As long as our class implements Java io. Serializable interface, you can use the writeobject() method of objectoutputstream to serialize an object; you can use the readobject() method of objectinputstream to return the read object. The serializable interface does not require us to implement any methods.

The following is an example, which can give us a perceptual understanding:

Serial implements Java io. Serializable interface is a class that needs to be serialized. We first construct a serial object Serial1, then save (serialize) it in a file, then read it out (deserialize) and print its contents.

  package Stream;

  /**

  * @author favo yang

  */

  import java.io.*;

  public class Serial implements Serializable {
  int company_id;
  String company_addr;
  boolean company_flag;
Public serial() {} / / different from C + +, it can be used without C + +
  public Serial(int company_id,String company_addr,boolean company_flag) {
  this.company_id=company_id;
  this.company_addr=company_addr;
  this.company_flag=company_flag;
  }

  public static void main(String[] args) {
  Serial serial1 = new Serial(752,”dayer street #5 building 02-287″,false);// Construct a new object
  FileInputStream in=null;
  FileOutputStream out=null;
  ObjectInputStream oin=null;
  ObjectOutputStream oout=null;

  try {
   out = new FileOutputStream(“5.txt”);
   oout = new ObjectOutputStream(out);
   serial1. serialize(oout);// serialize
   oout.close();
   oout=null;
   in = new FileInputStream(“5.txt”);
   oin = new ObjectInputStream(in);
   Serial serial2 = Serial. deserialize(oin);// Deserialization
   System. out. println(serial2);// Print results
  } catch (Exception ex){
   ex.printStackTrace();
  } finally{
   try {
    if (in != null) {
     in.close();
    }
    if (oin != null) {
     oin.close();
    }
    if (out != null) {
     out.close();
    }
    if (oout != null) {
     oout.close();
    }
   } catch (IOException ex1) {
    ex1.printStackTrace();
   }
  }
  }

  /**
  * deserialize
  */

  public static Serial deserialize(ObjectInputStream oin) throws Exception{
  Serial s=(Serial)oin.readObject();
  return s;
  }

  public String toString() {
  return “DATA: “+company_id+” “+company_addr+” “+company_flag;
  }

  /**
  * serialize
  */

  public void serialize(ObjectOutputStream oout) throws Exception{
  oout.writeObject(this);
  }
  }

Operation results:

  DATA: 752 dayer street #5 building 02-287 false
  
The results were printed correctly.