Java: How do I convert InputStream to GZIPInputStr

2019-04-09 18:47发布

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

2条回答
叼着烟拽天下
2楼-- · 2019-04-09 19:30

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.

查看更多
Rolldiameter
3楼-- · 2019-04-09 19:49

GZIPInputStream is for reading gzip-encoding content.

If your goal is to take a regular input stream and compress it in the GZIP format, then you need to write those bytes to a GZIPOutputStream.

See also this answer to a related question.

查看更多
登录 后发表回答