Skip to content

Instantly share code, notes, and snippets.

@bondolo
Created November 12, 2020 00:07
Show Gist options
  • Save bondolo/e88acace3fcf4517e24121fd6a0cf434 to your computer and use it in GitHub Desktop.
Save bondolo/e88acace3fcf4517e24121fd6a0cf434 to your computer and use it in GitHub Desktop.
Streaming GZIPOutputStream
/*
* Copyright © 2011 Mike Duigou. No rights reserved.
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
/**
* Extends GZIPOutputStream to improve behaviour of created streams for incrementally streamed content. This
* allows shorter reads on the receiving end to get the next uncompressed chunk and, for cases where the
* stream might fail unexpectedly, a greater chance of being able to read up to the end of the stream. The
* resulting stream may be slightly less efficiently compressed (higher overhead) than the default
* implementation, especially if the {@link #flush()} method is called frequently.
*
* @implSpec Flush compressed data to the output stream for each deflate operation.
*/
public class StreamingGZIPOutputStream extends GZIPOutputStream {
public StreamingGZIPOutputStream(OutputStream out) throws IOException {
this(out, 512);
}
public StreamingGZIPOutputStream(OutputStream out, int size) throws IOException {
super(out, size, true);
}
@Override
protected void deflate() throws IOException {
// This forces eager flush for each deflate operation
int len = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH);
if (len > 0) {
out.write(buf, 0, len);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment