Serialization details and instances of objects in Java

  • 2020-07-21 07:36:50
  • OfStack

Serialization details and instances of objects in Java

The process of converting an java object into a sequence of bytes is called object serialization.

The process of restoring a sequence of bytes to an java object is called object deserialization.

Purpose of object serialization:

1. Store the byte sequence of the object permanently on the hard disk, usually in one file
2. Byte serialization of objects transferred over the network

The void writeObject(Object obj) method serializes the obj object specified as an argument and writes the resulting sequence of bytes to a target output stream (writes the specified object to ObjectOutputStream).

The void readObject() method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them (read objects from ObjectInputStream).

Only class objects that implement the Serializable and Externalizable interfaces can be serialized.

The Externalizable interface inherits from the Serializable interface, and the classes that implement the Externalizable interface control the serialization behavior entirely by themselves, while the Serializable interface classes can take the default serialization approach


public static void readObj()throws Exception
  {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));

    Person p = (Person)ois.readObject();

    System.out.println(p);
    ois.close();
  }


 public static void writeObj()throws IOException
  {
    ObjectOutputStream oos = 
      new ObjectOutputStream(new FileOutputStream("obj.txt"));

    oos.writeObject(new Person("lisi0",399,"kr"));

    oos.close();
  }

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: