对象输入输出流
对象输入流:ObjectInputStream
构造方法:ObjectInputStream(InputStream in)
readObject
对象输出流:ObjectOutputStream
构造方法:ObjectOutputStream(OutputStream out)
writerObject
使用对象输出流写出对象,只能用对象输入流读取对象
只有支持java.io.Serializable接口的对象才能写入流中
对象输入流读取方法一
//method();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d.txt"));
try {
while (true){
Object obj = ois.readObject();
System.out.println(obj);
}
}catch (EOFException e){
}
ois.close();
}
private static void method() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d.txt"));
oos.writeObject(new Student("张三",18));
oos.writeObject(new Student("李四",17));
oos.close();
}
对象输入流读取方法二
//method1();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
Object obj = ois.readObject();
ArrayList<Student> array = (ArrayList<Student>) obj;
for (Student s : array) {
System.out.println(s);
}
ois.close();
}
private static void method1() throws IOException {
ArrayList<Student> array = new ArrayList<>();
array.add(new Student("张三",18));
array.add(new Student("李四",17));
array.add(new Student("王五",20));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));
oos.writeObject(array);
oos.close();
}
序列化接口
java.io.InvalidClassException
该类的序列版本号与从流中读取的类描述符的版本号不匹配
该类包含未知数据类型
该类没有可访问的无参数构造方法
idea如何自动生成序列号?
搜索serialVersionUID,选择GenerateSerialVersionUID