ObjectOutputStream
主函数
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("IO\\person.txt"));
oos.writeObject(new person("迪丽热巴",18));
oos.close();
类方法
public class person implements Serializable {
private String name;
private int age;
public person(String name, int age) {
this.name = name;
this.age = age;
}
}
Serializable 标记性接口
.
.
ObjectInputStream
反序列化
读取文件中的对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("IO\\person.txt"));
Object o = ois.readObject();
ois.close();
System.out.println(o);
person p = (person)o;
System.out.println(p.getName() + "=" + p.getAge());
输出结果:
.
.
InvalidClassException
当反序列化之前person类对象文件发生修改并且没有重新序列化
就会出现这个异常
原因是,序列号发生改变
错误原理:
解决方法:
在person类中把序列好设置为常量
private static final long serialVersionUID=1L;