-
序列化
将内存中的对象保存到硬盘上(ObjectOutputStream)
-
反序列化
从硬盘上将序列化的对象恢复到内存中(ObjectInputStream)
常用于服务之间调用时的数据传递
-
ObjectOutputStrem类
将Java对象的原始数据类型写出到文件,实现对象的持久化存储;
对象序列化条件:
-
必须实现Serializable接口
-
必须保证其所有属性均可序列化(即属性不能用transient修饰,该修饰为临时属性,不参与序列化)
package com.gh.no1; import java.io.*; public class Demo1 { public static void main(String[] args) throws IOException { // 序列化 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/xxx/Documents/IdeaProjects/gitProject/learn-projects/java-basics/student.txt")); Student bo = new Student("张三", 24); oos.writeObject(bo); oos.close(); System.out.print("序列化完成"); } }
-
-
ObjectInputStream类
将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
package com.gh.no1; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class Demo2 { public static void main(String[] args) throws IOException, ClassNotFoundException { // 反序列化 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/xxx/Documents/IdeaProjects/gitProject/learn-projects/java-basics/student.txt")); Student bo = (Student) ois.readObject(); System.out.println(bo.getName() + bo.getAge()); ois.close(); } }