Implementing in-memory compression for objects in Java

后端 未结 8 1894
忘了有多久
忘了有多久 2020-12-13 02:29

We have this use case where we would like to compress and store objects (in-memory) and decompress them as and when required.

The data we want to compress is quite

8条回答
  •  有刺的猬
    2020-12-13 02:47

    If you want to compress instances of MyObject you could have it implement Serializable and then stream the objects into a compressed byte array, like so:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
    ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
    objectOut.writeObject(myObj1);
    objectOut.writeObject(myObj2);
    objectOut.close();
    byte[] bytes = baos.toByteArray();
    

    Then to uncompress your byte[] back into the objects:

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    GZIPInputStream gzipIn = new GZIPInputStream(bais);
    ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
    MyObject myObj1 = (MyObject) objectIn.readObject();
    MyObject myObj2 = (MyObject) objectIn.readObject();
    objectIn.close();
    

提交回复
热议问题