Compress an InputStream with gzip

前端 未结 12 1436
迷失自我
迷失自我 2020-12-29 05:28

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 comp

12条回答
  •  太阳男子
    2020-12-29 06:34

    PipedOutputStream lets you write to a GZIPOutputStream and expose that data through an InputStream. It has a fixed memory cost, unlike other solutions which buffer the entire stream of data to an array or file. Only problem is you can't read and write from the same Thread, you have to use a separate one.

    private InputStream gzipInputStream(InputStream in) throws IOException {
        PipedInputStream zipped = new PipedInputStream();
        PipedOutputStream pipe = new PipedOutputStream(zipped);
        new Thread(
                () -> {
                    try(OutputStream zipper = new GZIPOutputStream(pipe)){
                        IOUtils.copy(in, zipper);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        ).start();
        return zipped;
    }
    

提交回复
热议问题