SoFunction
Updated on 2025-03-02

ObjectOutputStream class in Java

ObjectOutputStream is an output stream used in Java to serialize objects. It can convert the state information of Java objects into a byte stream for easy storage or transmission over the network.

Serialization is the process of converting an object into a byte stream, while deserialization is the process of restoring a byte stream into an object.

This article will introduce in detail the principles, usage methods and related code examples of ObjectOutputStream.

1. Introduction to ObjectOutputStream

Overview ObjectOutputStream is a class in the package that extends the OutputStream class for writing objects and basic data types into the output stream.

When the object is serialized, the field information of the object is saved, so that the object can be reconstructed at some point in the following time.

Main Methods Here are some of the main methods of the ObjectOutputStream class:

  • public ObjectOutputStream(OutputStream out): Creates an ObjectOutputStream object to write the object to the specified OutputStream.
  • public final void writeObject(Object obj): Writes the specified object to the ObjectOutputStream.
  • public void write(int b): Write one byte of data.
  • public void write(byte[] b): Write to an array of bytes.
  • public void flush(): Refresh the output stream to ensure that all data is written out.
  • public void close(): Close the output stream and release any system resources associated with it.

2. ObjectOutputStream usage steps

  • Create an ObjectOutputStream object;
  • Use the writeObject() method to serialize the object to the output stream;
  • Handle exceptions during serialization;
  • Turn off the output stream.

3. Code examples

Here is an example of object serialization using ObjectOutputStream:

Defining a serializable class First, we need to define a serializable class. Serializable classes need to implement the Serializable interface.

import ;
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    public Person(String name, int age) {
         = name;
         = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
         = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Serialize Object Serialize Person objects into a file.

import ;
import ;
public class ObjectOutputStreamExample {
    public static void main(String[] args) {
        try {
            Person person = new Person("Alice", 30);
            FileOutputStream fileOut = new FileOutputStream("");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            (person);
            ();
            ();
            ("Person object serialization succeeded!");
        } catch (Exception e) {
            ();
        }
    }
}

In the above code, we create a Person object and serialize it through an ObjectOutputStream to a namedin the file.

4. Things to note

  • serialVersionUID In a serializable class, it is recommended to explicitly declare a static constant called serialVersionUID to identify the version of the class. This ensures that during the deserialization process, the version of the class is consistent with the version at the time of serialization.
  • Transient keywords If a class's fields do not need to be serialized, you can use the transient keyword for modification. This way, when serializing the object, the field will not be included.
  • Parent class serialization If a class inherits from another class, the parent class also needs to implement the Serializable interface to ensure that the subclass object can be serialized.
  • writeObject and readObject methods In some cases, specific operations may be required during serialization and deserialization. It can be achieved by defining writeObject and readObject methods in the class.
  • Exception handling When serializing using ObjectOutputStream, exceptions may be thrown, such as IOException, etc. These exceptions need to be captured and processed. V. Extended content
  • Custom Serialization By adding writeObject and readObject methods to the class, you can customize the process of serialization and deserialization.
private void writeObject(ObjectOutputStream oos) throws IOException {
    // Custom serialization process    ();
    // Additional serialization logic can be added}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    // Custom deserialization process    ();
    // Additional deserialization logic can be added}

Externalizable interface In addition to implementing the Serializable interface, Externalizable interface can also be implemented to customize the process of serialization and deserialization.

Classes that implement the Externalizable interface must provide a parameterless constructor and require manual serialization of all fields.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.