Course contentsShow
← Java
Lesson 2113 of 2,87042. SerializationFree lesson

ObjectInputStream: Reading Objects from Streams

Learn how to create an ObjectInputStream and use readObject() to deserialize objects from a byte stream.

What You'll Learn

You'll learn how to create an ObjectInputStream and use readObject() to deserialize objects from a byte stream, reversing the serialization process you performed with ObjectOutputStream.

Reading Objects Back from Streams

After writing serialized objects to a stream, you need a way to reconstruct them in memory. ObjectInputStream is the counterpart to ObjectOutputStream—it reads the byte representation of objects and recreates them as fully functional Java objects.

Think of it like this: if ObjectOutputStream is a flash-freeze machine that preserves food for storage, ObjectInputStream is the thawing and reheating process that makes it edible again. The object "wakes up" with all its data intact.

Creating an ObjectInputStream

Wrap an ObjectInputStream around any InputStream, typically a FileInputStream:

try (FileInputStream fis = new FileInputStream("data.ser");
     ObjectInputStream ois = new ObjectInputStream(fis)) {
    // Ready to read objects
}

Using readObject() to Deserialize

The readObject() method reads the next object from the stream. It returns Object, so you must cast it to the expected type:

try (FileInputStream fis = new FileInputStream("person.ser");
     ObjectInputStream ois = new ObjectInputStream(fis)) {
    
    Person person = (Person) ois.readObject();
    System.out.println("Name: " + person.getName());
    
} catch (ClassNotFoundException e) {
    // Class definition not found during deserialization
    e.printStackTrace();
}

Notice you must handle ClassNotFoundException—this occurs if the class of the serialized object isn't available in the current classpath.

Order Matters

Objects must be read in the same order they were written. If you wrote three objects sequentially, you must read three objects in that exact sequence.

Key Takeaway: Use ObjectInputStream and readObject() to deserialize objects from byte streams, casting the result to the appropriate type and handling both IOException and ClassNotFoundException.