Search code examples
javagzipdeflate

How to output the results of deflater in GZIP format?


I'm using Java.

I want to use the Deflater class to deflate some input, then I want to output it in GZIP format so it could be unzipped with GZIP. How can I do this? My understanding is it will output it in a different format. I'm a noob, so if you could be explicit and maybe give a code example that would be super helpful.

I can't use GZIPOutputStream because I need to use some Deflater class specific features before outputting.


Solution

  • Apparently GZIPOutputStream uses Deflater under the hood anyway, so you're not trying to do anything all that crazy.

    One possibility (from this page, which is probably worth a read) is to subclass GZIPOutputStream so that you can access its Deflater object. Something more or less like this (untested):

    public class MyGZIPOutputStream extends GZIPOutputStream {
    
      public MyGZIPOutputStream(final OutputStream out) throws IOException {
        super(out);
      }
    
      public void setDictionary(byte[] b) {
        def.setDictionary(b);
      }
    
    }
    

    Then you can make your setDictionary call before using your MyGZIPOutputStream to save the file.

    The variable def is a protected member of GZIPOutputStream, so subclassing is necessary to access it.