java怎样强制刷新界面,在Java中强制刷新GZIPOutputStream

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.

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.

Best regards.

解决方案

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.

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

}

You can find the entire class in this jar (if you use Maven):

org.apache.tomcat

tomcat-coyote

7.0.8

Or just go and grab the source code FlushableGZIPOutputStream.java

It's released under the Apache-2.0 license.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值