Java serialization and deserialization involves the following steps: Writing a class that implements the Serializable interface into a stream (serialization). Read (deserialize) the object from the stream.
Serialization
Serializable
interface. ObjectOutputStream
object and associate it with a file or byte stream. ObjectOutputStream.writeObject()
method to write objects to the stream. Sample code:
import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class Employee implements Serializable { private String name; private int age; // 省略getter和setter方法 public static void main(String[] args) { Employee employee = new Employee("John", 30); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"))) { out.writeObject(employee); } catch (Exception e) { e.printStackTrace(); } } }
Deserialization
ObjectInputStream
object and associate it with a file or byte stream. ObjectInputStream.readObject()
method to read the object. Sample code:
import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializeEmployee { public static void main(String[] args) { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.txt"))) { Employee employee = (Employee) in.readObject(); System.out.println(employee.getName() + ", " + employee.getAge()); } catch (Exception e) { e.printStackTrace(); } } }
Notes:
Serializable
Only interface classes can be serialized. The above is the detailed content of What is the process of java serialization and deserialization?. For more information, please follow other related articles on the PHP Chinese website!