Fabien Fabien - 2 months ago 14
Java Question

Compress an InputStream with gzip

I would like to compress an input stream in java using Gzip compression.

Let's say we have an input stream (1GB of data..) not compressed. I want as a result a compressed inputstream from the source :

public InputStream getCompressedStream(InputStream unCompressedStream) {

// Not working because it's uncompressing the stream, I want the opposite.
return new GZIPInputStream(unCompressedStream);


kjp kjp

To compress data you need the GZIPOutputStream. But since you need to read the data back as if from an InputStream you need to convert the OutputStream to an InputStream. You can use getBytes() to do so:

GZIPOutputStream gout = new GZIPOutputStream();
//... Code to read from your original uncompressed data and write to gout.

//Convert to InputStream.
new ByteArrayInputStream(gout.getBytes());

But this method has the limitation that you need to read in all data first - and that means you have to have enough memory to hold that buffer.

Alternative approaches using Pipes are mentioned in this thread - Java - converting from OutputStream to InputStream