Compressing using the GZIP algorithm at runtime in Java

Use the standard API class GZIPOutputStream. Internally, it uses Deflater to compress data. The following example asks the user a file to compress and writes the compressed stream of data to file.gzip. If you want to compress multiple files to the same outputstream, you need to call finish to write the remaining compressed data without closing the stream. Otherwise, call close.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <file>");
         System.out.println("<file>.gzip will be created");
         System.exit(1);
      }
 
      try {
         FileInputStream fis = new FileInputStream(args[0]);
         FileOutputStream fos = new FileOutputStream(args[0] + ".gzip");
 
         GZIPOutputStream gos = new GZIPOutputStream(fos); 
         byte []buffer = new byte[1024];
         int l;
         while ((l = fis.read(buffer)) >= 0) {
            gos.write(buffer, 0, l);
         }
 
         // not necessary unless you want to write more files to the GZIPOutputStream
         // gos.finish();  
         gos.close();
         fis.close();
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}