You set the compression level in the Deflater constructor and pass that Deflater to the DeflaterOutputStream constructor.
This should about sort you:
DeflaterOutputStream dos = new DeflaterOutputStream(s, new Deflater(Deflater.BEST_COMPRESSION));
where s is the OutputStream that you are already using (probably a FileOutputStream
judging by your question)
Note that this is for DEFLATE, which is for the raw compression format used inside zip, gzip and a few other containers. Gzip adds extra headers and footers so you will not be able to write a .gz with this. GZIPOutputStream
does exist but does not seem to offer any way of setting the compression level (my Java is a little rusty but I'm pretty sure it does not inherit the constructor from DeflaterOutputStream).
If you actually wanted to write a .gz that other applications (such as winrar or "gunzip") could open, off the top of my head, you would need to add the headers and footers yourself. They aren't too hard, mostly just things like unix style permission masks in the headers and a crc32 at the end.
You may be able to pass a DeflaterOutputStream to the constructor of the GZIPOutputStream but this will probably compress it twice and when you extract the .gz file you will just get the original deflated file back anyway.
gzip is specified by RFC 1952
and is pretty simple.
Alternatively, of course, you could just package an operating system specific gzip binary with your application and execute it.
If you only want your own application to be able to read the files, DEFLATE should be fine.Edited by ghell - 6/12/10 at 5:42am