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

This commit is contained in:
xx
2026-10-26 11:33:12 +08:00
parent a55901e29f
commit 49591d0e10
2 changed files with 44 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
package com.inmind.xlh03;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/*
14.序列化流保存对象(ObjectOutputStream)
构造方法:
ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
常用方法:
void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。
*/
public class Demo08 {
public static void main(String[] args) throws Exception{
//创建一个学生对象
Student s = new Student("张三", 18);
//创建序列化流对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
//将对象写出到文件中
oos.writeObject(s);
oos.close();
}
}
+21
View File
@@ -0,0 +1,21 @@
package com.inmind.xlh03;
import java.io.Serializable;
//Serializable:该接口是允许序列化的接口
public class Student implements Serializable {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}