在Java中为对象实现内存中压缩 [英] Implementing in-memory compression for objects in Java

查看:730
本文介绍了在Java中为对象实现内存中压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这个用例,我们想压缩和存储对象(内存中),并在需要时解压缩它们。

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 varied, from float vectors to strings to dates.

建议任何良好的压缩技术来做到这一点?

Can someone suggest any good compression technique to do this ?

我们正在把压缩的容易性和减压的速度作为最重要的因素。

We are looking at ease of compression and speed of decompression as the most important factors.

感谢。

推荐答案

如果要压缩 MyObject 你可以让它实现 Serializable ,然后将对象流化为压缩的字节数组,如下:

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();

然后解压缩您的 byte [] 到对象中:

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();

这篇关于在Java中为对象实现内存中压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆