对象的反序列化流ObjectInputStream

该流位于API中java,io.ObjectInputStream,作用是将文件中的对象,反序列化为,以流的方式读取出来

ObjectInputStream中的构造方法

ObjectInputStream(InputStream in)创建从指定 InputStream 读取的 ObjectInputStream

ObjectInputStream中特有的成员方法

Object readObject()从 ObjectInputStream 读取对象

ObjectInputStream的使用步骤

  1. 创建ObjectInputStream对象,构造方法中传递字节输入流
  2. 使用ObjectInputStream对象中的readObject方法读取文件中的对象
  3. 释放资源
  4. 使用读取出来的对象

举例示范

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文件

posted @ 2020-11-05 11:44  谢海川  阅读(38)  评论(0)    收藏  举报