Basic Serialization: Writing and Reading a Single Object
You'll learn: How to serialize a single object to a file and then deserialize it back into memory with a complete working example.
The Complete Workflow
Now that you know about ObjectOutputStream and ObjectInputStream, let's see them work together in a real scenario. Think of it like taking a photo of your object's state (serialization), saving it to your album (file), and later pulling that exact snapshot back out to recreate the object (deserialization).
Writing an Object to a File
First, you create an ObjectOutputStream wrapping a FileOutputStream, then call writeObject():
import java.io.*;
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Serialization
Person person = new Person("Alice", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.ser"))) {
oos.writeObject(person);
System.out.println("Person object written to file.");
} catch (IOException e) {
e.printStackTrace();
}
Reading the Object Back
Next, use ObjectInputStream to read the file and cast the result back to your type:
// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.ser"))) {
Person restoredPerson = (Person) ois.readObject();
System.out.println("Name: " + restoredPerson.name);
System.out.println("Age: " + restoredPerson.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
Notice the cast is required because readObject() returns Object, and you must handle ClassNotFoundException in case the class definition isn't available.
Key Takeaway: Serializing and deserializing a single object involves creating an ObjectOutputStream to write with writeObject(), saving to a file, then creating an ObjectInputStream to read with readObject(), casting the result back to your original type.