首页 > 其他分享 >对象的序列化与反序列化

对象的序列化与反序列化

时间:2022-10-08 21:55:50浏览次数:48  
标签:ObjectOutputStream ObjectInputStream 对象 list new 序列化

ObjectOutputStream对象序列化流

作用:把对象以流的形式写入道文件中保存

  • 构造方法:ObjectOutputStream(OutputStream out)

  • 特有的方法:

    • void writeObject(Object obj)将指定的对象写入道ObjectOutputStream中
  • 注意:序列化和反序列化的时候,会抛出NotSerializableException异常,类必须实现Serializable接口来开启序列化,这个接口也叫标记型接口

 public static void main(String[] args)throws Exception {
        ArrayList<Person> list =  new ArrayList<>();
        list.add(new Person("张三",20));
        list.add(new Person("李四",19));
        list.add(new Person("王五",22));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/PersonList.txt"));
        oos.writeObject(list);
        oos.close();
    }

ObjectInputStream对象反序列化流

作用:把文件中保存的对象,以流的方式读取出来使用

  • 构造方法:

    • ObjectInputStream(InputStream in)参数为字节输入流
  • 特有的成员方法:

    • Object readObject() 从ObjectInputStream读取对象。
  • 使用步骤:

    1. 创建ObjectInputStream对象,构造方法中传递字节输入流
    2. 使用ObjectInputStream对象中的readObject读取保存对象的文件
    3. 释放资源
 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/PersonList.txt"));
        ArrayList<Person> list =(ArrayList<Person>) ois.readObject();
        for (Person item :list) {
            System.out.println(item.getName()+":"+item.getAge());
        }
        ois.close();

注意事项:

  1. static关键字:

    • 静态关键字,被static修饰的成员变量,不能被序列化
  2. transient关键字:

    • transient只能修饰变量,不能修饰方法和类
    • 瞬态关键字,被transient修饰的成员变量,不能被序列化

标签:ObjectOutputStream,ObjectInputStream,对象,list,new,序列化
From: https://www.cnblogs.com/-xyk/p/16770380.html

相关文章