Java - 压缩输出字节数组的大小
当使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
deflate
后,调用finished
查看是否还有更多内容要输出。 例如:如果您只想收集内存中的所有字节,您可以使用 ByteArrayOutputStream。 例如:
After calling
deflate
, callfinished
to see if it still has more to output. eg:If you just want to collect all of the bytes in-memory you can use a ByteArrayOutputStream. eg:
为什么 Java 将类错误地拼写为“deflater”? 这个词就是“紧缩指数”。 天啊! 抱歉,我必须把这件事从心里说出来。
如前所述,预期用途是继续调用 deflate 直到获得压缩的所有输出。 但是,如果您确实想在一次调用中完成此操作,那么 deflate 可以扩展数据的量是有限制的。 不幸的是,Java 没有提供 zlib 中的一个名为
deflateBound()
的函数,它提供了那个上限。 您可以只使用该函数的保守界限,并将相关行复制到此处: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 calleddeflateBound()
which provides that upper bound. You can just use the conservative bound from that function, with the relevant line copied here: