s-day10-序列化流保存对象(ObjectOutputStream)

This commit is contained in:
2026-08-12 11:19:24 +08:00
parent 473def2b44
commit cfd3bcb417
2 changed files with 47 additions and 0 deletions
@@ -0,0 +1,26 @@
package com.inmind.object_stream03;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/*
序列化流保存对象(ObjectOutputStream)
构造方法:
ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
常用方法:
void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。
*/
public class Demo09 {
public static void main(String[] args) throws Exception {
Student student = new Student("张三", 18);
//获取序列化流对象,写出对象(将对象保存到文件中)
FileOutputStream fos = new FileOutputStream("student.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//注意:如果要序列化对象,对应的类,必须支持序列化操作,也就是实现Serializable,类似一个标记的功能,表示可以序列化
oos.writeObject(student);
oos.close();
}
}
@@ -0,0 +1,21 @@
package com.inmind.object_stream03;
import java.io.Serializable;
public class Student implements Serializable {
String name;
int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}