Home > database >  InputStream to GZIPInputStream, and I need to know the size of the GZIPInputStream
InputStream to GZIPInputStream, and I need to know the size of the GZIPInputStream

Time:02-02

I have a MultipartFile and I need to compress inputStream as gzip and sent it, but I need to find a way to compress it and know the compressed size of it


param: MultipartFile file

        try(var inputStream = file.getInputStream()) {

            var outputStream = new GZIPOutputStream(OutputStream.nullOutputStream());

            IOUtils.copyLarge(inputStream, outputStream);

           var compressedInputStream = someConvertMerthod(outputStream);


            sendCompressed(compressedInputStream, compressedSize)
        }

Maybe I can do something like this Java: How do I convert InputStream to GZIPInputStream? but I am not gonna be a able to get the compressedSize

I am not finding an easy way to do it :(

CodePudding user response:

CopyLarge() returns the number of bytes copied. I would assume this is true even if the output is discarded, so all you need is to capture the return value of IOUtils.copyLarge(in,out) and you should be good to go, but this does assume the return value is bytes WRITTEN and not bytes READ, which is not really documented. So it might work!

In general though, you are assuming you can turn the output stream back into an input stream, so nullOutputStream() is not going to be an option. Instead you will be creating a temp file, writing your compressed data to it, and then closing it. At that point you can simply ask the file system API how big it is, that should be iron clad.

CodePudding user response:

hey I think I found the solution :)

    param: MultipartFile file

            try (InputStream inputStream = file.getInputStream()) {

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);

                inputStream.transferTo(gzipOutputStream);
                InputStream compressedInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

                byteArrayOutputStream.size() // is the compressed size      


            }

Thanks guys!

  • Related