进阶day10-.反序列化流读取对象(ObjectInputStream)

This commit is contained in:
2026-03-23 16:28:11 +08:00
parent 3631315995
commit 822f7b4810

View File

@@ -0,0 +1,30 @@
package com.inmind.object_stream03;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.function.Supplier;
/*
反序列化流读取对象(ObjectInputStream)
构造方法:
ObjectInputStream(InputStream in) 创建从指定的InputStream读取的ObjectInputStream。
常用方法:
Object readObject() 从ObjectInputStream读取一个对象。
*/
public class Demo12 {
//将之前的student.txt读取到java进程中生成一个叫张三18的Student对象
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));
Object o = ois.readObject();
if (o instanceof Student) {
Student s = ((Student) o);
System.out.println(s.name);
System.out.println(s.age);
}
ois.close();
}
}