ObjectOutputStream: Writing Objects to Streams
What You'll Learn
You'll learn how to use ObjectOutputStream to serialize Java objects into byte streams, enabling you to save object state to files or transmit it over networks.
The Core Idea
Now that you understand what serialization is and how to make classes serializable, it's time to actually perform serialization. ObjectOutputStream is your tool for this job—it takes serializable objects and converts them into a sequence of bytes that can be written to any output destination.
Think of ObjectOutputStream as a translator that converts your living, breathing Java objects into a flat "blueprint" format that can be stored or transmitted. Just as you might compress a piece of furniture flat for shipping, ObjectOutputStream flattens your object's state into bytes.
Creating an ObjectOutputStream
You wrap an existing OutputStream (like a FileOutputStream) with an ObjectOutputStream:
try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
Employee emp = new Employee("Alice", 50000);
out.writeObject(emp); // Serialize the object
} catch (IOException e) {
e.printStackTrace();
}
The writeObject() Method
The writeObject() method does the heavy lifting. It:
- Inspects the object's class metadata
- Writes all serializable instance fields
- Recursively serializes referenced objects
- Handles the entire object graph automatically
You can call writeObject() multiple times to write several objects to the same stream—they'll be stored sequentially.
Key Points
- Always wrap
ObjectOutputStreamaround anotherOutputStream - Use try-with-resources to ensure proper stream closure
- The
.serextension is conventional for serialized files - Objects must implement
Serializableor you'll getNotSerializableException
Key Takeaway: ObjectOutputStream and its writeObject() method convert serializable Java objects into byte streams, enabling persistent storage or network transmission of object state.