Serializing Multiple Objects in Sequence
You'll learn how to write and read multiple objects one after another using ObjectOutputStream and ObjectInputStream.
The Core Idea
Just as you can write one object to a stream, you can write several objects in sequence to the same stream. When reading them back, you retrieve them in the exact same order—think of it like sending multiple packages through a single mail chute, then collecting them at the other end in the order they arrived.
Writing Multiple Objects
You use the same ObjectOutputStream and call writeObject() multiple times:
try (FileOutputStream fos = new FileOutputStream("data.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
String message = "Hello";
Integer count = 42;
Double price = 19.99;
oos.writeObject(message); // First object
oos.writeObject(count); // Second object
oos.writeObject(price); // Third object
}
Reading Multiple Objects
To read them back, call readObject() the same number of times, in the same order:
try (FileInputStream fis = new FileInputStream("data.ser");
ObjectInputStream ois = new ObjectInputStream(fis)) {
String message = (String) ois.readObject(); // First
Integer count = (Integer) ois.readObject(); // Second
Double price = (Double) ois.readObject(); // Third
System.out.println(message + ", " + count + ", " + price);
}
Important Points
- Order matters: Objects must be read in the exact order they were written
- Type casting: You must cast each object back to its original type
- EOF detection: Reading past the last object throws
EOFException - Each call to
writeObject()serializes one complete object and its entire object graph
Key Takeaway: You can serialize multiple objects sequentially by calling writeObject() multiple times on the same ObjectOutputStream, then read them back in identical order using readObject() on the ObjectInputStream.