This Program checks for the existance of the file or directory which is intended for zipping and does the zipping of the same. The user need to provide the location of the file or directory (mandatory) and the location to which it needs to be zipped (optional).
import java.io.*; import java.util.zip.*; public class zipUtil { public static void main(String a[]) { // Requires at least one param with a non-null value! if (a.length == 0) { System.err .println("Usage: filename with location is required and zipping location is optional"); return; } try { String inputPath = a[0]; String outPath; File file = new File(inputPath); boolean exists = file.exists(); // checks file existance String fname = file.getName(); String absolutePath = file.getAbsolutePath(); // gets absolutepath // of the inputfile // gets inputfile's parent directory path to use incase extraction // location is not provided by enduser. String inputfilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator)); if (exists) { // It returns false if File or directory does not exist System.out.println("the file or directory for zipping " + inputPath + " does exist"); } else { // It returns true if File or directory exists System.out.println("the file or directory for zipping " + inputPath + " does not exist"); throw new FileNotFoundException(); } // checks for extraction location argument if (a.length == 2) { outPath = a[1]; } else { outPath = inputfilePath; } if (!outPath.endsWith("/")) outPath += "/"; File inFolder = new File(inputPath); File outFolder = new File(outPath + fname + ".zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(outFolder))); BufferedInputStream in = null; byte[] data = new byte[1000]; String files[] = inFolder.list(); for (int i = 0; i < files.length; i++) { in = new BufferedInputStream(new FileInputStream( inFolder.getPath() + "/" + files[i]), 1000); out.putNextEntry(new ZipEntry(files[i])); int count; while ((count = in.read(data, 0, 1000)) != -1) { out.write(data, 0, count); } out.closeEntry(); } out.flush(); out.close(); } catch (FileNotFoundException ioe) { System.err.println("this file not found"); return; } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } } }