Create Zip Files Using Java


Creating zip file in Java is super easy & fun too!
For convenience, I have taken two files (one excel & one word document) and my java program will zip both the file in a single zip file with a given name.

Note: Using very minor customization you can create a application for any number of file and any type of documents.

public class CreateZip {
 /**
  * Takes two hard-coded files in your machine 
  * And
  * Zips both of them in a single zip file
  * 
  */
 public void zipFiles() {
  FileOutputStream fos = null;
  ZipOutputStream zipOut = null;
  try {
   fos = new FileOutputStream(
     "C:\\Users\\sghosh\\Desktop\\testing.zip");
   String url = "C:\\Users\\sghosh\\Desktop\\Document for Menu Permission Tap.doc";
   String url1 = "C:\\Users\\sghosh\\Desktop\\KT Plan for PJ.xls";

   String fileName1 = url.substring(url.lastIndexOf("\\")+1);
   String fileName2 = url1.substring(url.lastIndexOf("\\")+1);
   
   zipOut = new ZipOutputStream(new BufferedOutputStream(fos));

   BufferedInputStream input = new BufferedInputStream(
     new FileInputStream(url));
   BufferedInputStream input1 = new BufferedInputStream(
     new FileInputStream(url1));
   ZipEntry ze = new ZipEntry(fileName1);
   System.out
     .println("Zipping the file: "+fileName1);
   zipOut.putNextEntry(ze);
   byte[] tmp = new byte[4 * 1024];
   int size = 0;
   while ((size = input.read(tmp)) != -1) {
    zipOut.write(tmp, 0, size);
   }
   ze = new ZipEntry(fileName2);
   System.out.println("Zipping the file: "+fileName2);
   zipOut.putNextEntry(ze);
   while ((size = input1.read(tmp)) != -1) {
    zipOut.write(tmp, 0, size);
   }
   zipOut.flush();
   input1.close();
   input.close();
   zipOut.close();
   System.out.println("Done... Zipped the files...");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fos != null)
     fos.close();
   } catch (IOException ex) {

   }
  }
 }

 /**
  * @param a
  * Main method for this class
  */
 public static void main(String a[]) {
  CreateZip mfe = new CreateZip();
  mfe.zipFiles();
 }
}

It's super easy... Happy Learning!

No comments :

Post a Comment