Implement serialization and deserialization of objects and binary data based on ObjectOutputStream

Table of contents

Why do we need to serialize it?

How to implement serialization and deserialization of objects and binary data?


Why do we need to serialize it?


Mainly to convert an object (structured data) into a string/byte array to facilitate our storage (sometimes we need to store data in a file, and files can only store string/binary data, which is inconvenient to store directly store objects) and transmit data (transmit it over the network).

How to implement serialization and deserialization of objects and binary data?


In fact, there are many solutions for binary serialization:

1. The Java standard library provides serialization solutions, ObjectInputStream and ObjectOutputStream (recommended).

2. Hessian.

3. protobuffer

4. thrift.

5. JSON can also be used to represent binary data through some conversions (there are many special symbols in JSON format: " {} These symbols will affect the parsing of JSON format): binary data can be base64 encoded. The function of base64 is to use 4 bytes Representing 3-byte information will ensure that all 4 bytes use text characters (equivalent to converting binary data into text. Just like embedding a picture in HTML, the binary base64 encoding of the picture can be directly encoded as text. The form is embedded into HTML), but the base64 solution is inefficient, has additional transcoding overhead, and will also increase the space.

Ps: Here we use solution one, which is the solution that comes with the standard library. The biggest advantage of this solution is that there is no need to introduce additional dependencies.

The specific implementation is as follows:

  1. First of all, if you want this object to be serializable or deserialized, you need this class to implement the Serializable interface (without rewriting any methods)
  2. ByteArrayOutputStream: Serialize the object into a byte array. The stream object is equivalent to a variable-length byte array. The data is serialized through the object, and then gradually written into the ByteArrayOutputStream, and then uniformly converted into byte[].
  3. ByteArrayInputStream: Deserialize the byte array into an object, hand the binary data that needs to be converted to byteArrayInputStream, and then hand byteArrayInputStream to ObjectInputStream, and then use the readObject method to deserialize it into an object.
public class BinaryTool {

    /**
     * 把一个对象序列化成一个字节数组
     * @param object
     * @return
     */
    public static byte[] toBytes(Object object) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                //此处 writeObject 就会把该对象进行序列化,生成的二进制字节数据,写入到 ObjectOutputStream 中
                //又由于 ObjectOutputStream 又关联到了 ByteArrayOutputStream,最终就写入到了 ByteArrayOutputStream
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    /**
     * 把一个字节数组反序列化成对象
     * @param data
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                //此处的 readObject 就是从 data 这个 byte 中读取数据并进行反序列化
                object = objectInputStream.readObject();
            }
        }
        return object;
    }

}

Ps: Don’t confuse the concepts of input and output

Both inputstream and  outputstream  are definitions of streams. The center of these two operations is memory, so to understand their differences, the key is to understand the exchange of memory and other containers.

Memory-------------》Screen outputstreamScreen
-------------》Memory inputstream

Memory-------------》The hard disk outoutstream is followed by the write operation. Write writes the content into the hard disk file.
The hard disk-------------》The memory inputstream is followed by the read operation. read reads content from the hard disk into memory and then operates on it.
 

Guess you like

Origin blog.csdn.net/CYK_byte/article/details/132265020