序列化流和反序列化流

序列化流

使用 ObjectOutputStream 方法,把基本流包装成高级流

用 writeObject 写到文件中去

但直接写会出现 NotSerializableException 异常,所以要让Javabean类实现 Serializable 接口

//实现 Serializable 接口
class student implements Serializable{
    private String name;
    private int age;
    public student(){}
    public student(String name,int age){
        this.name=name;
        this.age=age;
    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}
public class aaa {
    public static void main(String[] args) throws IOException {
        student stu=new student("aaa",18);
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("a.txt"));
        oos.writeObject(stu);
        oos.close();
    }
}

反序列化流

使用 ObjectInputStream

用 readObject 读取

class student implements Serializable{
    private String name;
    private int age;
    public student(){}
    public student(String name,int age){
        this.name=name;
        this.age=age;
    }
    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}
public class aaa {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("a.txt"));
        student o=(student) ois.readObject();
        System.out.println(o);
        ois.close();
    }
}

版本号不匹配解决方法

如果出现stream classdesc serialVersionUID = XXXXXXXXXXXXXXXXXX, local class serialVersionUID = YYYYYYYYYYYYYYYY 的错误, 说明文件中的版本号和 Javabean 的版本号不匹配

解决方法: 手段添加版本号

class student implements Serializable{
    //添加版本号
    @Serial
    private static final long serialVersionUID = 3455536973241020155L;

    private String name;
    private int age;
    public student(){}
    public student(String name,int age){
        this.name=name;
        this.age=age;
    }
    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

初学者,见解不足,如有错误请指出

你可能感兴趣的:(#,io流,java,前端,开发语言)