Java: How do I convert InputStream to GZIPInputStream?

daydreamer picture daydreamer · Sep 7, 2012 · Viewed 8.1k times · Source

I have a method like

      public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
        // a.) create gzip of inputStream
        final GZIPInputStream zipInputStream;
        try {
            zipInputStream = new GZIPInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
        }

I wan to convert the inputStream into zipInputStream, what is the way to do that?

  • The above method is incorrect and throws Exception as "Not a Zip Format"

converting Java Streams to me are really confusing and I do not make them right

Answer

BalusC picture BalusC · Sep 7, 2012

The GZIPInputStream is to be used to decompress an incoming InputStream. To compress an incoming InputStream using GZIP, you basically need to write it to a GZIPOutputStream.

You can get a new InputStream out of it if you use ByteArrayOutputStream to write gzipped content to a byte[] and ByteArrayInputStream to turn a byte[] into an InputStream.

So, basically:

public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
    final InputStream zipInputStream;
    try {
        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutput = new GZIPOutputStream(bytesOutput);

        try {
            byte[] buffer = new byte[10240];
            for (int length = 0; (length = inputStream.read(buffer)) != -1;) {
                gzipOutput.write(buffer, 0, length);
            }
        } finally {
            try { inputStream.close(); } catch (IOException ignore) {}
            try { gzipOutput.close(); } catch (IOException ignore) {}
        }

        zipInputStream = new ByteArrayInputStream(bytesOutput.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
        throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
    }

    // ...

You can if necessary replace the ByteArrayOutputStream/ByteArrayInputStream by a FileOuputStream/FileInputStream on a temporary file as created by File#createTempFile(), especially if those streams can contain large data which might overflow machine's available memory when used concurrently.