Question:
How to compress a file in GZIP format?
Code:
import java.io.*; import java.util.zip.GZIPOutputStream; public class GZipFile { public static void main( String[] args ) { String input = "/tmp/file.txt"; String output = "/tmp/file.txt.gz"; byte[] buffer = new byte[1024]; try { FileInputStream in = new FileInputStream(input); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(fos); int len; while ((len = in.read(buffer)) > 0) { gzos.write(buffer, 0, len); } in.close(); gzos.finish(); gzos.close(); System.out.println("Done"); } catch(Exception ex) { System.out.println(ex); } } }
Output:
$ java GZipFile Done $ ls -l /tmp/file.txt -rw-rw-r-- 1 dennis dennis 4880 Feb 26 16:42 /tmp/file.txt $ ls -l /tmp/file.txt.gz -rw-rw-r-- 1 dennis dennis 56 Feb 26 16:44 /tmp/file.txt.gz