Java基础--对象序列化

1.序列化与反序列化

把内存中的对象永久保存到硬盘的过程称为对象序列化,也叫做持久化。

把硬盘持久化的内存恢复的内存的过程称为对象反序列化。

2.Serializable接口

类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化,并抛出异常

Serializable接口没有方法或字段,仅用于标识可序列化的语义

3.序列化对象

ObjectOutputStream 继承于OutputStream,专门用于把对象序列化到本地。提供了writeObject() 用于写入一个对象。

 1 public static void main(String[] args) throws IOException {
 2         
 3         Student stu = new Student("001", "大狗", 20, Gender.男);
 4         
 5         /**
 6          *    方案1:取stu所有的属性,通过特定的字符串(-),把各个属性值连接起来
 7          *  001-大狗-20-男
 8          */
 9         
10         File file = new File("d:\javatest\l.txt");
11         FileOutputStream out = new FileOutputStream(file);
12         ObjectOutputStream oos = new ObjectOutputStream(out);
13         
14         oos.writeObject(stu);
15         
16         oos.close();
17         out.close();
18     }

4.反序列化对象

 1 public static void main(String[] args) throws IOException, ClassNotFoundException {
 2         
 3         File file = new File("d:\javatest\l.txt");
 4         
 5         
 6         FileInputStream in = new FileInputStream(file);
 7         ObjectInputStream ois = new ObjectInputStream(in);
 8         
 9         Student student = (Student) ois.readObject();
10         System.out.println(student.getId());
11         System.out.println(student.getName());
12         System.out.println(student.getAge());
13         System.out.println(student.getGender());
14         
15         ois.close();
16         in.close();
17     }

5.序列化版本

当序列化完成后,后期升级程序中的类(Student),此时再反序列化时会出现异常。

异常原因:序列化流的serialVersionUID和升级后类的版本不匹配。

解决方案:给Student类加序列化版本号,有两种方式

【1】default serial version ID 生成默认的serial version ID 一般值都是1L。

【2】generated serial version ID 根据当前类的属性、方法生成一个唯一ID。

1 public class Student implements Serializable {
2 
3     private static final long serialVersionUID = -1003763572517930507L;

6.transient

开发过程中,如果想忽略某些字段不让其序列化时,可以使用transient修饰。

1 public class Student implements Serializable {
2 
3     private static final long serialVersionUID = 7222966748321328300L;
4 
5     private String id;
6     private transient String name;
7     private transient int age;
8     private Gender gender;
9     private String phone;
原文地址:https://www.cnblogs.com/WhiperHong/p/10828495.html