6

I have a class which has a method that is receiving an object as a parameter. This method is invoked via RMI.

public RMIClass extends Serializable {
    public RMIMethod(MyFile file){
        // do stuff
    }
}

MyFile has a property called "body", which is a byte array.

public final class MyFile implements Serializable {

    private byte[] body = new byte[0];
    //.... 

    public byte[] getBody() {
        return body;
    }
    //....
}

This property holds the gzipped data of a file that was parsed by another application.

I need to decompress this byte array before performing further actions with it.

All the examples I see of decompressing gzipped data assume that I want to write it to the disk and create a physical file, which I do not.

How do I do this?

Thanks in advance.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
rshepherd
  • 1,396
  • 3
  • 12
  • 21

5 Answers5

10

Wrap your byte array with a ByteArrayInputStream and feed it into a GZipInputStream

basszero
  • 29,624
  • 9
  • 57
  • 79
  • example code can be found here: https://stackoverflow.com/questions/23606047/decompressing-to-a-byte-using-gzipinputstream – Amos Feb 11 '19 at 12:09
2

JDK 9+

  private byte[] gzipUncompress(byte[] compressedBytes) throws IOException {
    try (InputStream inputStream = new GZIPInputStream(new ByteArrayInputStream(compressedBytes))) {
      try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        inputStream.transferTo(outputStream);
        return outputStream.toByteArray();
      }
    }

}

Tony BenBrahim
  • 7,040
  • 2
  • 36
  • 49
1

Look at those samples, and wherever they're using FileOutputStream, use ByteArrayOutputStream instead. Wherever they're using FileInputStream, use ByteArrayInputStream instead. The rest should be simple.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Why don't you create your own class that extends OutputStream or , whatever is the archive writing to ?

Geo
  • 93,257
  • 117
  • 344
  • 520
0

If you want to write to a ByteBuffer you can do this.

private static void uncompress(final byte[] input, final ByteBuffer output) throws IOException
    {
        final GZIPInputStream inputGzipStream = new GZIPInputStream(new ByteArrayInputStream(input));
        Channels.newChannel(inputGzipStream).read(output);
    }
Judd
  • 31
  • 3