【问题标题】:Java - How to do Gzip compression of java objectJava - 如何对 Java 对象进行 Gzip 压缩
【发布时间】:2020-02-09 15:31:38
【问题描述】:

如何使用 Gzip 压缩 Java pojo 对象?

下面的代码压缩一个字符串 -

public static String compress(String str, String inEncoding) {
        if (str == null || str.length() == 0) {
            return str;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(inEncoding));
            gzip.close();
            return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

代替String str作为参数,如何使用下面的pojo类对象(Client cc)并进行压缩?

Pojo 类 -

Class client {
Public string name;
Public string location;
//Getter and setter methods
}

如何使用 gzip 压缩和解压缩这个客户端 pojo 类?

【问题讨论】:

  • 您标记了 json,那么为什么不将 POJO 转换为 JSON,它是一个字符串值,然后您可以使用现有代码对其进行压缩?
  • 仅供参考: 不要将ByteArrayOutputStream 解码为String。相反,使用 Base64 编码对字节进行编码。
  • pojo会有大容量数据,将近1GB。因此,将 pojo 转换为 jaon 字符串可能在内存消耗方面存在问题。
  • 那你为什么要标记你的问题json?如果您知道不需要 JSON,请删除该标签。 --- 无论如何,如果您使用流式 JSON 生成器并直接压缩文本输出,这不是问题。

标签: java json compression gzip


【解决方案1】:

您可以通过执行以下操作来压缩使用 gzip 实现可序列化的 Client 类:

public static bytes[] compressThis(Client client){
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  GZIPOutputStream gzipOut = new GZIPOutputStream(client);
  ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
  objectOut.writeObject(client);
  objectOut.close();
  return baos.toByteArray();
}

你可以通过以下方式解压:

public static getClientFrom(bytes[] bytes){
  ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  GZIPInputStream gzipIn = new GZIPInputStream(bais);
  ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
  Client client = (Client) objectIn.readObject();
  objectIn.close();
  return client;
}

【讨论】:

  • 谢谢。我猜这使用默认压缩进行压缩。是否可以在 Gzip 中指定类似 utf-8 或 utf-16 的编码?如何查看压缩前后客户端类对象的大小?
  • 尺寸?数一下bytes.length
  • Gzip 是一种用于压缩而不是编码的算法。根据定义编码正在改变格式(例如:nary、hex、decimal、base64、DER、BER),这些格式(通常)并不意味着改变数据的含义。尺寸扩大/缩小当然可能是不同编码的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多