
Java
The purpose of Serialization is to help us achieve whatever complicated scenario we just witnessed in an easier manner.
Working with ObjectOutputStream and ObjectInputStream
The magic of basic serialization happens with just two methods: one to serialize objects and write them to a stream, and a second to read from the stream and deserialize the object.
ObjectOutputStream.writeObject() - serialize and write
ObjectInputStream.readObject() - read and deserialize
The Java.io.ObjectOutputStream and Java.io.ObjectInputStream classes are considered to be higher-level classes in the Java.io package, and as we learned in the previous chapter that means that you'll wrap them around lower-level classes, such as Java.io.FileOutputStream and Java.io.FileInputStream. Here's a small program that creates an object, serializes it, and then deserializes it:
import Java.io.*;
class Car implements Serializable { } // 1
public class SerializeCar {
public static void main(String[] args) {
Car c = new Car(); // 2
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream OS = new ObjectOutputStream(fs);
OS.writeObject(c); // 3
OS.close();
} Catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Car) ois.readObject(); // 4
ois.close();
} Catch (Exception e) { e.printStackTrace(); }
}
}
Let's take a look at the key points in this example:
1. We declare that the Car class implements the Serializable interface. Serializable is a marker interface; it has no methods to implement.
2. We make a new Car object, which as we know is serializable.
3. We serialize the Car object c by invoking the writeObject() method. First, we had to put all of our I/O-related code in a try/Catch block. Next we had to create a FileOutputStream to write the object to. Then we wrapped the FileOutputStream in an ObjectOutputStream, which is the class that has the magic serialization method that we need. Remember that the invocation of writeObject() performs two tasks: it serializes the object, and then it writes the serialized object to a file.
4. We de-serialize the Car object by invoking the readObject() method. The readObject() method returns an Object, so we have to cast the deserialized object back to a Car. Again, we had to go through the typical I/O hoops to set this up.
This is a simple example of serialization in action.
Copyright © 2026 eLLeNow.com All Rights Reserved.