序列化和反序列化的基本使用

package demo02;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @description: demo12
 * @author: liuyang
 * @create: 2021-09-07 10:08
 */
public class Demo12 {
    /**
     * 序列化和反序列化的要求:
     * 被序列化的类及其所有引用类型的属性都需要实现Serializable接口,
     * 被序列化的类及其所有引用类型的属性都需要显示的增加serialVersionUID常量,
     * static和transient修饰的属性不可以被序列化。
     */
    @Test
    public void test1() {
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            // 对象输出流
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("object.txt"));
            // 对象输入流
            objectInputStream = new ObjectInputStream(new FileInputStream("object.txt"));
            // 序列化对象,Person对象需实现Serializable接口
            objectOutputStream.writeObject(new Person("刘阳", 28));
            objectOutputStream.writeObject(new Person("杨静", 23));
            // 反序列化对象,按照写入的顺序反序列化
            Person person1 = (Person) objectInputStream.readObject();
            System.out.println(person1);
            Person person2 = (Person) objectInputStream.readObject();
            System.out.println(person2);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
class Person implements Serializable {
    private static final long serialVersionUID = 962066480350311916L;
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 

posted @ 2021-09-07 17:10  牛牛的自留地  阅读(36)  评论(0编辑  收藏  举报