Java 序列化和反序列化涉及以下步骤:将实现了 Serializable 接口的类写入流中(序列化)。将对象从流中读取(反序列化)。
序列化
Serializable
接口的类。ObjectOutputStream
对象,并将其与一个文件或字节流关联。ObjectOutputStream.writeObject()
方法将对象写入流中。示例代码:
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(); } } }
反序列化
ObjectInputStream
对象,并将其与一个文件或字节流关联。ObjectInputStream.readObject()
方法读取对象。示例代码:
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(); } } }
注意事项:
Serializable
接口的类才能进行序列化。以上是java序列化反序列化的过程是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!