乐闻世界logo
搜索文章和话题

What is the difference between Serialization and Deserialization in Java?

1个答案

1

Serialization and deserialization are two complementary processes in Java, primarily used to convert an object's state into a format that can be stored or transmitted, and to reconstruct the object afterward.

Serialization refers to the process of converting an object's state information into a data format that can be saved to a file, stored in a database, or transmitted over a network. In Java, this is typically achieved by implementing the java.io.Serializable interface. The serialized format can be binary streams or text-based formats such as XML and JSON.

For example, suppose we have an instance of the Employee class, and we want to save its state to a file for future use. We can serialize the object as follows:

java
Employee employee = new Employee("John", "Developer", 30); FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(employee); out.close(); fileOut.close();

This code creates an Employee object and serializes it to a file named employee.ser using the ObjectOutputStream class.

Deserialization is the inverse process of serialization, converting previously serialized data back into the original object state. This is typically achieved by reading the serialized data and converting it back to the original object state.

Continuing with the previous example, if we want to restore the state of the Employee object from the file, we can deserialize it as follows:

java
FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Employee e = (Employee) in.readObject(); in.close(); fileIn.close();

This code reads the serialized data from the file employee.ser and converts it back to an Employee class object using the ObjectInputStream class.

In summary, serialization and deserialization are complementary processes; serialization is used for object storage and transmission, while deserialization is used to restore the object's state. They are very useful in scenarios such as distributed computing, persistent storage, and deep copying.

2024年8月7日 21:57 回复

你的答案