Java 序列化

package 序列化;

import java.io.*;

public class 序列化 {
    public static void main(String[] args) throws Exception {
        对象序列化();
        反序列化();
    }

    //一次序列化要对应一次反序列化
    private static void 反序列化() throws Exception {
        String out = "D:\\API.txt";
        ObjectInputStream OIS = new ObjectInputStream(new FileInputStream(out));
        Object o = OIS.readObject();
        System.out.println(o);
        OIS.close();
    }

    private static void 对象序列化() throws Exception {
        String out = "D:\\API.txt";
        Stu stu = new Stu("QianL", 12);
        ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(out));
        //OOS.writeObject(OOS);
        OOS.writeObject(stu);
        OOS.close();
        System.out.println("序列化成功");
    }
}

//序列化必须 implements  Serializable
class Stu implements Serializable {
    //以下代码固定代码序列号
    //private static final long serialVersionUID = 1L;
    public String name;
    public int age;

    public Stu(String Name, int Age) {
        name = Name;
        age = Age;
    }

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

上一篇:实验7


下一篇:2021.9.7使用DQL查询数据(一)