devxlogo

Serializing and Deserializing Objects

Serializing and Deserializing Objects

The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object of type MyClass is serialized and deserialized.

 1.    // Serialize an object of type MyClass2.    MyClass  myObject = new MyClass();3.    FileOutputStream fos = new FileOutputStream("myObject.ser");4.    ObjectOutputStream oos = new ObjectOutputStream(fos);5.    oos.writeObject(myObject);6.    oos.flush();7.    oos.close();8. 9.    // Deserialize the object persisted in "myObject.ser"10. FileInputStream fis = new FileInputStream("myObject.ser");11. ObjectInputStream ois = new ObjectInputStream(fis);12. MyClass myDeserializedObject = (MyClass)ois.readObject();13. ois.close();

Lines 1-5 serialize the object myObject of type MyClass. On Line 3, the file output stream fos is created for the file named myObject.ser. The object is actually persisted in this file on Lines 5-7. Lines 9-13 read the object back from the file myObject.ser. If you list the files in the directory where this code’s .class file is stored, you will see a new file called myObject.ser added to the listing. The Lines 1-7 and 9-13 can be in two completely different processes run at different times.

See also  Small Business Strategies with Venmo
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist