【IO编程】5.对象流

1. 序列化与反序列化

  1. 序列化:保存数据时,保存数据的值数据类型
  2. 反序列化:恢复数据时,恢复数据的值数据类型
  3. 某个类的对象若想序列化,该类必须实现Serializable接口或Externalizable接口
    • Serializable接口是一个标记接口,没有方法
    • Externalizable接口需要有方法实现,因此一般使用Serializable接口

2. ObjectOutputStream介绍

ObjectOutputStream提供对基本类型或对象类型的序列化的方法。

image-20210719000721509

  • 构造方法
    • ObjectOutputStream(OutputStream out)
      • 输出流对象
  • 成员方法
    • void writeInt(int val)
      • 序列化整型
    • void writeLong(long val)
      • 序列化长整型
    • void writeFloat(float val)
      • 序列化单精度浮点型
    • void writeDouble(double val)
      • 序列化双精度浮点型
    • void writeChar(int val)
      • 序列化字符型
    • void writeUTF(String str)
      • 序列化字符串
    • void writeObject(Object obj)
      • 序列化对象,该对象需要实现Serializable接口
    • void close()
      • 关闭流,需要捕获IO异常

将数据序列化代码如下:

@Test
public void serialize() {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("e:\\test.data"));
        oos.writeInt(1);
        oos.writeLong(2);
        oos.writeFloat(3.0F);
        oos.writeDouble(4.0);
        oos.writeChar(5);
        oos.writeUTF("6");
        oos.writeObject(new Exception("exception"));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3. ObjectInputStream介绍

image-20210719000743878

ObjectInputStream提供对基本类型或对象类型的反序列化的方法。

  • 构造方法
    • ObjectInputStream(InputStream in)
      • 输入流对象
  • 成员方法
    • int readInt()
      • 反序列化得到整型
    • long readLong()
      • 反序列化得到长整型
    • float readFloat()
      • 反序列化得到单精度浮点型
    • double readDouble()
      • 反序列化得到双精度浮点型
    • int readChar()
      • 反序列化得到字符型
    • String readUTF()
      • 反序列化得到字符串
    • Object readObject()
      • 反序列化得到对象
    • void close()
      • 关闭流,需要捕获IO异常

将数据反序列化代码如下:

@Test
public void deserialize() {
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("e:\\test.data"));
        System.out.println(ois.readInt());
        System.out.println(ois.readLong());
        System.out.println(ois.readFloat());
        System.out.println(ois.readDouble());
        System.out.println(ois.readChar());
        System.out.println(ois.readUTF());
        System.out.println(ois.readObject());
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. 对象流细节说明

  1. 读写顺序需要一致
  2. 序列化或反序列化对象需要实现Serializable接口
  3. 序列化的类添加SerialVersionUID可以提高版本的兼容性
  4. 序列化对象时默认将里面所有的属性都序列化,除非static和transient修饰
  5. 序列化对象时,属性的类型也必须实现序列化接口
  6. 序列化具备可继承性
posted @ 2021-07-21 14:16  haojinglei  阅读(52)  评论(0)    收藏  举报