ObjectOutputStream
- 将 Java 对象的基本数据类型和图形写入 OutputStream。
- 可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。
- 如果流是网络套接字流,则可以在另一台主机上或另一个进程中重构对象。
父类:OutputStream
代码:
public static void main(String[] args) throws IOException {
Student stu1 = new Student("张三", 20, "男",new Teacher("谭老师"));
Student stu2 = new Student("李四", 30, "女",new Teacher("王老师"));
Student stu3 = new Student("王五", 40, "男",new Teacher("李老师"));
//1 创建对象输出流(序列化流--将对象流化) 把java中的对象,
通过流的方式保存在文件中--对象流化
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("student.txt"));
//2:写把对象写入文件
/* oos.writeObject(stu1);
oos.writeObject(stu2);
oos.writeObject(stu3);
oos.writeObject(null); //自定义结束点
*/ //2 先把对象保存在集合中
ArrayList<Student> al = new ArrayList<>();
al.add(stu1);
al.add(stu2);
al.add(stu3);
//3:直接把集合保存到文件
oos.writeObject(al);
//3:关闭流
oos.close();
}