您的位置:

ObjectInputStream及其相关知识

一、对象的序列化和反序列化

1、对象的序列化和反序列化

/**
 * 将对象序列化到文件中
 *
 * @param obj 对象
 * @param file 文件
 * @throws IOException IO异常
 */
public static void writeObjectToFile(Object obj, File file) throws IOException {
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
        oos.writeObject(obj);
    }
}

/**
 * 从文件中反序列化得到对象
 *
 * @param file 文件
 * @param   对象类型
 * @return 反序列化得到的对象
 * @throws IOException            IO异常
 * @throws ClassNotFoundException 找不到类异常
 */
public static 
    T readObjectFromFile(File file) throws IOException, ClassNotFoundException {
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
        return (T) ois.readObject();
    }
}
   
  

2、对象的序列化和反序列化例子

public class SerializeObject {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        File file = new File("object.txt");
        Student studentSrc = new Student("Tom", 18);

        writeObjectToFile(studentSrc, file);

        Student studentDst = readObjectFromFile(file);
        System.out.println("studentDst = " + studentDst);
    }
}

class Student implements Serializable {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

二、ObjectInputStream类的详解

1、ObjectInputStream类简介

public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {
    protected ObjectInputStream() throws IOException, SecurityException {}

    public ObjectInputStream(InputStream in) throws IOException {
        verifySubclass();
        bin = new BlockDataInputStream(in);
        handles = new HandleTable(10);
        vlist = new ValidationList();
    }

    private final BlockDataInput bin;
    // more code omitted
}

2、ObjectInputStream类的方法

/**
 *从流中读取一个Object对象
 *
 * @throws IOException            IO异常
 * @throws ClassNotFoundException 找不到类异常
 */
public final Object readObject() throws IOException, ClassNotFoundException { /* more code */ }

/**
 * 从流中读取一个boolean类型的值
 *
 * @throws IOException IO异常
 */
public boolean readBoolean() throws IOException { /* more code */ } 

三、ObjectOutputStream类及其相关类的详解

1、ObjectOutputStream类简介

public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants {
    /** 写入对象 */
    public void writeObject(Object obj) throws IOException {...}

    /** 获取包含此流中的所有对象曾经的引用 */
    protected ObjectStreamClass getObjectStreamClass(Class cl) throws IOException, ClassNotFoundException {...}

    /** 写入单个字节 */
    public void write(int val) throws IOException {...}

    /** 实现数据写入底层的操作系统 */
    public void flush() throws IOException {...}

    /** 关闭对象输出流 */
    public void close() throws IOException {...}
}

final class BlockDataOutputStream {...}
final class BlockDataInputStream {...}

2、ObjectOutputStream类的方法

/**
 * 将指定的基本类型写入流中。
 */
public final void writeInt(int val) throws IOException { /* more code */ }

/**
 * 将单个double精度浮点数写入流中
 */
public final void writeDouble(double val) throws IOException { /* more code */ }

/**
 * 写入一个UTF-8编码格式的字符串
 */
public final void writeUTF(String str) throws IOException { /* more code */ }

四、常用工具类的使用

1、IOUtils类

/**
 * 将InputStream转为byte[]
 *
 * @param inputStream 输入流
 * @return byte[]
 * @throws IOException IO异常
 */
public static byte[] toByteArray(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 4];
    int n;
    while (-1 != (n = inputStream.read(buffer))) {
        byteArrayOutputStream.write(buffer, 0, n);
    }
    return byteArrayOutputStream.toByteArray();
}

2、ByteArrayUtils类

/**
 * 将序列化字节数组转为指定类型的对象
 *
 * @param bytes 序列化字节数组
 * @param clazz 指定类型
 * @param    类型
 * @return 对象
 * @throws IOException            IO异常
 * @throws ClassNotFoundException 找不到类异常
 */
public static 
    T deserialize(byte[] bytes, Class
     clazz) throws IOException, ClassNotFoundException {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInputStream ois = new ObjectInputStream(bis)) {
        return (T) ois.readObject();
    }
}

/**
 * 将对象序列化为字节数组
 *
 * @param obj 对象
 * @return 序列化字节数组
 * @throws IOException IO异常
 */
public static byte[] serialize(Object obj) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(bos)) {
        oos.writeObject(obj);
        return bos.toByteArray();
    }
}
    
   
  

五、总结

本文主要介绍了对象的序列化和反序列化知识及其相关类,同时也介绍了常用工具类的使用。通过学习,我们了解了对象的序列化和反序列化的原理和方法,了解了ObjectInputStream、ObjectOutputStream、BlockDataOutputStream、BlockDataInputStream等相关类的详细信息,以及IOUtils和ByteArrayUtils这两个常用的工具类的使用方法。希望对你的学习和工作有所帮助。