18

GZIPOutputStream をフラッシュする (強制的に圧縮してデータを送信する) 必要があるプログラムに取り組んでいます。問題は、GZIPOutputStream のフラッシュ メソッドが期待どおりに機能せず (圧縮を強制してデータを送信する)、代わりに Stream が効率的なデータ圧縮のためにさらにデータを待機することです。

finish を呼び出すと、データは圧縮され、出力ストリームを介して送信されますが、GZIPOutputStream (基になるストリームではない) が閉じられるため、新しい GZIPOutputStream を作成するまでデータを書き込むことができず、時間とパフォーマンスが犠牲になります。

誰でもこれを手伝ってくれることを願っています。

よろしくお願いします。

4

6 に答える 6

12

私はまだこれを試していません。このアドバイスは、Java 7が手元にあるまで役に立ちませんが、から継承されたGZIPOutputStreamのメソッドのドキュメントは、構築時に指定されたフラッシュモードに依存してます。圧縮する保留中のデータをフラッシュするかどうかを決定します。この議論は、建設時にも受け入れられます。flush()DeflaterOutputStreamsyncFlushDeflater#SYNC_FLUSHsyncFlushGZIPOutputStream

Deflator#SYNC_FLUSHどちらか、または多分使用したいようですDeflater#FULL_FLUSHが、ここまで掘り下げる前に、まず2引数または4引数のGZIPOutputStreamコンストラクターtrueを使用して、引数を渡してみてsyncFlushください。これにより、必要なフラッシュ動作がアクティブになります。

于 2010-09-03T23:11:01.090 に答える
11

うまくいく他の答えが見つかりませんでした。GZIPOutputStream が使用しているネイティブ コードがデータを保持しているため、まだフラッシュを拒否しています。

ありがたいことに、誰かが FlushableGZIPOutputStream を Apache Tomcat プロジェクトの一部として実装していることを発見しました。ここに魔法の部分があります:

@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 を使用している場合)。

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-coyote</artifactId>
    <version>7.0.8</version>
</dependency>

または、ソースコードFlushableGZIPOutputStream.javaを入手してください。

Apache-2.0 ライセンスの下でリリースされています。

于 2013-02-15T03:14:53.553 に答える
2

このコードは、私のアプリケーションでうまく機能しています。

public class StreamingGZIPOutputStream extends GZIPOutputStream {

    public StreamingGZIPOutputStream(OutputStream out) throws IOException {
        super(out);
    }

    @Override
    protected void deflate() throws IOException {
        // SYNC_FLUSH is the key here, because it causes writing to the output
        // stream in a streaming manner instead of waiting until the entire
        // contents of the response are known.  for a large 1 MB json example
        // this took the size from around 48k to around 50k, so the benefits
        // of sending data to the client sooner seem to far outweigh the
        // added data sent due to less efficient compression
        int len = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH);
        if (len > 0) {
            out.write(buf, 0, len);
        }
    }

}
于 2015-08-10T18:54:07.587 に答える
1

にも同じ問題がAndroidあります。def.setLevel(Deflater.NO_COMPRESSION);例外がスローされるため、アクセプターの回答は機能しません。方法に応じflushて の圧縮レベルを変更しますDeflater。したがって、データを書き込む前に圧縮の変更を呼び出す必要があると思いますが、よくわかりません。

他に 2 つのオプションがあります。

于 2014-12-17T18:45:17.150 に答える
1

バグ ID 4813885がこの問題を処理します。2006 年 9 月 9 日に提出された "DamonHD" のコメント (バグレポートの約半分) には、彼がJazzlib の .xml のFlushableGZIPOutputStream上に構築した例が含まれています。 net.sf.jazzlib.DeflaterOutputStream

参考までに、(再フォーマットされた)抜粋を次に示します。

/**
 * Substitute for GZIPOutputStream that maximises compression and has a usable
 * flush(). This is also more careful about its output writes for efficiency,
 * and indeed buffers them to minimise the number of write()s downstream which
 * is especially useful where each write() has a cost such as an OS call, a disc
 * write, or a network packet.
 */
public class FlushableGZIPOutputStream extends net.sf.jazzlib.DeflaterOutputStream {
    private final CRC32 crc = new CRC32();
    private final static int GZIP_MAGIC = 0x8b1f;
    private final OutputStream os;

    /** Set when input has arrived and not yet been compressed and flushed downstream. */
    private boolean somethingWritten;

    public FlushableGZIPOutputStream(final OutputStream os) throws IOException {
        this(os, 8192);
    }

    public FlushableGZIPOutputStream(final OutputStream os, final int bufsize) throws IOException {
        super(new FilterOutputStream(new BufferedOutputStream(os, bufsize)) {
            /** Suppress inappropriate/inefficient flush()es by DeflaterOutputStream. */
            @Override
            public void flush() {
            }
        }, new net.sf.jazzlib.Deflater(net.sf.jazzlib.Deflater.BEST_COMPRESSION, true));
        this.os = os;
        writeHeader();
        crc.reset();
    }

    public synchronized void write(byte[] buf, int off, int len) throws IOException {
        somethingWritten = true;
        super.write(buf, off, len);
        crc.update(buf, off, len);
    }

    /**
     * Flush any accumulated input downstream in compressed form. We overcome
     * some bugs/misfeatures here so that:
     * <ul>
     * <li>We won't allow the GZIP header to be flushed on its own without real compressed
     * data in the same write downstream. 
     * <li>We ensure that any accumulated uncompressed data really is forced through the 
     * compressor.
     * <li>We prevent spurious empty compressed blocks being produced from successive 
     * flush()es with no intervening new data.
     * </ul>
     */
    @Override
    public synchronized void flush() throws IOException {
        if (!somethingWritten) { return; }

        // We call this to get def.flush() called,
        // but suppress the (usually premature) out.flush() called internally.
        super.flush();

        // Since super.flush() seems to fail to reliably force output, 
        // possibly due to over-cautious def.needsInput() guard following def.flush(),
        // we try to force the issue here by bypassing the guard.
        int len;
        while((len = def.deflate(buf, 0, buf.length)) > 0) {
            out.write(buf, 0, len);
        }

        // Really flush the stream below us...
        os.flush();

        // Further flush()es ignored until more input data data written.
        somethingWritten = false;
    }

    public synchronized void close() throws IOException {
        if (!def.finished()) {
            def.finish();
            do {
                int len = def.deflate(buf, 0, buf.length);
                if (len <= 0) { 
                    break;
                }
                out.write(buf, 0, len);
            } while (!def.finished());
        }

        // Write trailer
        out.write(generateTrailer());

        out.close();
    }

    // ...
}

役に立つかもしれません。

于 2010-09-04T01:29:19.257 に答える