进阶day10-.序列化流保存对象(ObjectOutputStream)

This commit is contained in:
2026-03-23 16:15:09 +08:00
parent 259a84c1ae
commit 3631315995
2 changed files with 44 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package com.inmind.object_stream03;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/*
序列化流对象(ObjectOutputStream)
构造方法:
ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
常用方法:
void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。
注意要进行序列化被序列化的对象类必须实现一个接口Serializable,否则会报NotSerializableException
*/
public class Demo11 {
public static void main(String[] args) throws IOException {
Student s = new Student("张三", 20);
//序列化将java对象保存到文件中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
oos.writeObject(s);
oos.close();
}
}

View File

@@ -0,0 +1,15 @@
package com.inmind.object_stream03;
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;
}
}