Reading and Writing Serialized Objects to File in Java

Serialization is the process of converting an object into a stream of bytes, allowing it to be easily stored or transferred. In Java, serialized objects are commonly stored or transmitted as files. These files can later be read to recreate the original object. In this article, we will explore how to read and write serialized objects to a file in Java.

Serializing an Object to File

To serialize an object in Java, the class being serialized must implement the java.io.Serializable interface, which indicates that an object can be serialized. Let's take a look at an example where we serialize an object and save it to a file:

import java.io.*;

public class ObjectSerializer {

    public static void main(String[] args) {
        // Creating an object to serialize
        MyClass obj = new MyClass("John Doe", 25);

        try {
            // Creating a file output stream
            FileOutputStream fileOut = new FileOutputStream("object.ser");

            // Creating an object output stream
            ObjectOutputStream objOut = new ObjectOutputStream(fileOut);

            // Writing the object to the output stream
            objOut.writeObject(obj);

            // Closing the streams
            objOut.close();
            fileOut.close();

            System.out.println("Object serialized and saved to file successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // A sample class to serialize
    static class MyClass implements Serializable {
        private String name;
        private int age;

        public MyClass(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // Getter methods for name and age
        // ...
    }
}

In the above example, we create an object of the MyClass and serialize it using the ObjectOutputStream. We write the serialized object to a file called object.ser. Finally, the output stream is closed.

Deserializing an Object from File

Now, let's see how we can read and deserialize the object back from the file:

import java.io.*;

public class ObjectDeserializer {

    public static void main(String[] args) {
        try {
            // Creating a file input stream
            FileInputStream fileIn = new FileInputStream("object.ser");

            // Creating an object input stream
            ObjectInputStream objIn = new ObjectInputStream(fileIn);

            // Reading the object from the input stream
            MyClass obj = (MyClass) objIn.readObject();

            // Closing the streams
            objIn.close();
            fileIn.close();

            // Accessing the deserialized object's properties
            System.out.println("Name: " + obj.getName());
            System.out.println("Age: " + obj.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // MyClass definition goes here...
}

In this example, we create a FileInputStream to read the serialized object from the file object.ser. The ObjectInputStream is then used to read the object from the input stream. We cast the deserialized object to its original type and access its properties. Finally, the streams are closed.

Conclusion

Serializing and deserializing objects in Java allows us to store and retrieve complex objects conveniently. By implementing the Serializable interface and using the appropriate input/output streams, we can easily save objects to files or transmit them over networks. Remember to handle any potential exceptions that may occur during the serialization and deserialization processes to ensure consistent and reliable code.


noob to master © copyleft