Java: How do I convert InputStream to GZIPInputStream?

霸气de小男生 提交于 2020-01-01 10:40:52

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12322073/java-how-do-i-convert-inputstream-to-gzipinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!