Zipping a file in Java

The following example creates a zip file of the file that you provide at command line.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      FileOutputStream fos = new FileOutputStream(args[0] + ".zip");
      BufferedOutputStream bos = new BufferedOutputStream(fos);
      ZipOutputStream zos = new ZipOutputStream(bos);
 
      File inFile = new File(args[0]);
      FileInputStream fis = new FileInputStream(inFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      
      ZipEntry zipEntry = new ZipEntry(inFile.toString());
      zipEntry.setMethod(ZipEntry.DEFLATED);
      zos.putNextEntry(zipEntry);
 
      byte[] buffer = new byte[1024];
      int length;
      while ((length = bis.read(buffer)) != -1) {
         zos.write(buffer, 0, length);
      }
  
      zos.closeEntry();
      zos.close();
      bis.close();
   }
}