该流位于API中java,io.ObjectInputStream
,作用是将文件中的对象,反序列化为,以流的方式读取出来
ObjectInputStream中的构造方法
ObjectInputStream(InputStream in)
创建从指定 InputStream 读取的 ObjectInputStream
ObjectInputStream中特有的成员方法
Object readObject()
从 ObjectInputStream 读取对象
ObjectInputStream的使用步骤
- 创建ObjectInputStream对象,构造方法中传递字节输入流
- 使用ObjectInputStream对象中的readObject方法读取文件中的对象
- 释放资源
- 使用读取出来的对象
举例示范
public class Person implements Serializable {
String name = "张三";
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\d.txt"));
Object o = ois.readObject();
ois.close();
System.out.println(o);
}
得到的结果为:
反序列化的前提
1、类必须实现Serializable
2、必须存在类对应的class文件