在Java中的GZIPOutputStream上强制刷新 [英] Force flush on a GZIPOutputStream in java
问题描述
我们正在开发一个程序,需要刷新(强制压缩和发送数据)GZIPOutputStream.问题在于,GZIPOutputStream的flush方法无法按预期方式工作(强制压缩并发送数据),而是Stream等待更多数据以进行有效的数据压缩.
we are working on a program where we need to flush (force compress and send data) a GZIPOutputStream. The problem is, that the flush method of the GZIPOutputStream doesn't work as expected (force compress and send data), instead the Stream waits for more data for efficient data compression.
调用完成后,数据将被压缩并通过输出流发送,但GZIPOutputStream(而不是基础流)将被关闭,因此在创建新的GZIPOutputStream之前,我们无法写入更多数据,这会浪费时间和性能.
When you call finish the data is compressed and sent over the output stream but the GZIPOutputStream (not the underlying stream) will be closed so we cant write more data till we create a new GZIPOutputStream, which costs time and performance.
希望任何人都可以提供帮助.
Hope anyone can help with this.
最诚挚的问候.
推荐答案
我没有找到其他可行的答案.它仍然拒绝刷新,因为GZIPOutputStream使用的本机代码保留了数据.
I didn't find the other answer to work. It still refused to flush because the native code that GZIPOutputStream is using holds onto the data.
很幸运,我发现有人在Apache Tomcat项目中实现了FlushableGZIPOutputStream.这是魔术部分:
Thankfully, I discovered that someone has implemented a FlushableGZIPOutputStream as part of the Apache Tomcat project. Here is the magic part:
@Override
public synchronized void flush() throws IOException {
if (hasLastByte) {
// - do not allow the gzip header to be flushed on its own
// - do not do anything if there is no data to send
// trick the deflater to flush
/**
* Now this is tricky: We force the Deflater to flush its data by
* switching compression level. As yet, a perplexingly simple workaround
* for
* http://developer.java.sun.com/developer/bugParade/bugs/4255743.html
*/
if (!def.finished()) {
def.setLevel(Deflater.NO_COMPRESSION);
flushLastByte();
flagReenableCompression = true;
}
}
out.flush();
}
您可以在此jar中找到整个类(如果使用Maven):
You can find the entire class in this jar (if you use Maven):
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>7.0.8</version>
</dependency>
Or just go and grab the source code FlushableGZIPOutputStream.java
它是根据Apache-2.0许可证发行的.
It's released under the Apache-2.0 license.
这篇关于在Java中的GZIPOutputStream上强制刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!