1.通过集合实现多个对象序列化
public class ObjectOutputStreamDemo02 {
public static void main(String[] args) throws Exception {
//创建对象输出流
FileOutputStream fos = new FileOutputStream("C:\\Users\\Public\\Documents\\hhh.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//实例化对象,创建1个ArrayList数组,把对象添加到数组中
Student s1 = new Student("刘德华", 20);
Student s2 = new Student("张学友", 19);
Student s3 = new Student("林志玲", 21);
ArrayList<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
//将对象输出到文件(序列化过程)
oos.writeObject(students);
//关闭流通道
oos.close();
System.out.println("序列化执行完毕");
}
}
2.通过集合实现多个对象反序列化
public class ObjectInputStreamDemo02 {
public static void main(String[] args) throws Exception {
//1.创建对象输出流
FileInputStream fis = new FileInputStream("C:\\Users\\Public\\Documents\\hhh.txt ");
ObjectInputStream ois = new ObjectInputStream(fis);
//读取对象文件
ArrayList<Student> s = (ArrayList<Student>) ois.readObject();
System.out.println(s.toString());
//关闭
ois.close();
System.out.println("反序列化执行完毕");
}
}

被折叠的 条评论
为什么被折叠?



