首页 > 技术文章 > 47 对象流

flypigggg 2021-04-11 17:15 原文

对象流

ObjectInputStream

ObjectOutputStream

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可
以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
序列化:用ObjectOutputStream类保存基本类型数据或对象的机制

反序列化:用ObjectlnputStream类读取基本类型数据或对象的机制
ObjectOutputStreamObjectInputStream不能序列化 static 和 transient 修饰的成员变量

transient(透明的):想让某个不要序列化,就加上

序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去

要想一个Java对象时可序列化的,需要满足相应的要求:见Person类

Person类需要满足如下的要求,方可序列化:

实例化Serializable 接口,public static final long serialVersionUID = 4212545415112L;要加上这个常量,数字可以随便改

除了当前Person类需要实例化Serializable 接口之外,还必须保证其内部所有属性也必须是可序列化的

    @Test
    public void test1(){

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));

            oos.writeObject(new String("我爱中国"));
            oos.flush();//刷新操作

            oos.writeObject(new Person("刘狗",23));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

反序列化:将磁盘文件中的对象还原为内存中的一个java对象

 @Test
    public void testObjectInputStream(){

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String)obj;

            Person p = (Person)ois.readObject();
            System.out.println(p);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

推荐阅读