ObjectInputStream and ObjectOutputStream in Java

In Java, the classes ObjectInputStream and ObjectOutputStream are used for object serialization and deserialization. Serialization refers to the process of converting an object into a byte stream so that it can be saved to a file, transmitted over a network, or stored in memory for later use. Deserialization is the reverse process, where a byte stream is converted back into an object.


ObjectOutputStream: Serializing Objects

The ObjectOutputStream class is used to write (serialize) Java objects to an output stream, typically to a file. It allows you to save objects in a form that can be restored later.

Basic Syntax for ObjectOutputStream:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"));

Key Methods:

  • writeObject(Object obj): Serializes the specified object and writes it to the underlying output stream.
Code Example

Explanation:

  • We create an instance of the Student class and serialize it using ObjectOutputStream.
  • The serialized object is saved to a file named student.ser.

ObjectInputStream: Deserializing Objects

The ObjectInputStream class is used to read (deserialize) objects from an input stream, such as a file or a network connection. It reconstructs an object from its byte stream form.

Basic Syntax for ObjectInputStream:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));

Key Methods:

  • Object readObject(): Reads an object from the input stream and deserializes it.
Code Example

Explanation:

  • We deserialize the Student object previously serialized and saved in student.ser.
  • The readObject() method reads the object from the file and reconstructs it as a Student object.

Important Points to Understand

Serialization and Deserialization Process

  • Serialization: Convert an object to a byte stream for storage or transmission.
    • This process includes saving all fields of the object.
  • Deserialization: Convert a byte stream back to an object.

The Serializable Interface

  • Serializable: A marker interface in Java that a class must implement for its objects to be serialized.
  • serialVersionUID: A unique identifier for each class that is used during deserialization to ensure that a loaded class matches the serialized object.

    private static final long serialVersionUID = 1L;
    

Transient Fields

  • The transient keyword is used for fields that you don't want to serialize.
  • Fields marked as transient are not included in the serialization process.

Externalizable Interface

  • While Serializable is used for default serialization, you can also implement Externalizable to control the serialization process manually.