Java - 压缩输出字节数组的大小

发布于 2024-07-29 03:24:01 字数 132 浏览 3 评论 0原文

当使用java.util.zip.Deflater的deflate方法时,必须提供一个byte[]作为参数,该byte[]应该初始化为多大? 我读过,不能保证压缩数据会比未压缩数据更小。 我应该遵循一定比例的输入吗? 目前我将其设置为输入的两倍

When using the deflate-method of java.util.zip.Deflater, a byte[] has to be supplied as the argument, how big should that byte[] be initialized to? I've read there's no guarantee the compressed data will even be smaller that the uncompressed data. Is there a certain % of the input I should go with?
Currently I make it twice as big as the input

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扬花落满肩 2024-08-05 03:24:01

调用 deflate 后,调用 finished 查看是否还有更多内容要输出。 例如:

byte[] buffer = new byte[BUFFER_SIZE];
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  // deal with the n bytes in out here
}

如果您只想收集内存中的所有字节,您可以使用 ByteArrayOutputStream。 例如:

byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  baos.write(buffer, 0, n);
}
return baos.toByteArray();

After calling deflate, call finished to see if it still has more to output. eg:

byte[] buffer = new byte[BUFFER_SIZE];
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  // deal with the n bytes in out here
}

If you just want to collect all of the bytes in-memory you can use a ByteArrayOutputStream. eg:

byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (!deflater.finished()) {
  int n = deflater.deflate(buffer);
  baos.write(buffer, 0, n);
}
return baos.toByteArray();
牵你手 2024-08-05 03:24:01

为什么 Java 将类错误地拼写为“deflater”? 这个词就是“紧缩指数”。 天啊! 抱歉,我必须把这件事从心里说出来。

如前所述,预期用途是继续调用 deflate 直到获得压缩的所有输出。 但是,如果您确实想在一次调用中完成此操作,那么 deflate 可以扩展数据的量是有限制的。 不幸的是,Java 没有提供 zlib 中的一个名为 deflateBound() 的函数,它提供了那个上限。 您可以只使用该函数的保守界限,并将相关行复制到此处:

complen = sourceLen +
          ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;

Why does Java misspell the class as "deflater"? The word is "deflator". Jeez! Sorry, had to get that off my chest.

As noted, the expected use is to keep calling deflate until you get all of the output from the compression. However, if you really want to do it in a single call, then there is a bound on the amount by which deflate can expand the data. There is a function in zlib that Java unfortunately does not make available called deflateBound() which provides that upper bound. You can just use the conservative bound from that function, with the relevant line copied here:

complen = sourceLen +
          ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文