tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Zip Utilities > Zip Directory

Zip Directory 

The following example shows creating a ZIP file out of user given directory. It iterates through all sub directories recursively and updates ZIP entries. The method zipOut.putNextEntry() adds a new file entry to the ZIP file. Remove the drive prefix before making an entry to build the ZIP file in proper format. It handles both empty and non-empty directories. If a ZIP Entry name ends with "/" then its treated as directory entry. So to create a directory in ZIP file suffix the entry name with "/".

Check the source of ZipEntry.

ZipEntry.java  
public boolean isDirectory()
{
  return this.name.endsWith("/");
}

File Name  :  
com/bethecoder/tutorials/utils/zip/ZipDirectory.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDirectory {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] argsthrows IOException {
    zipDirectory("C:\\NEW2""C:\\pqr.zip");
    System.out.println("Done..");
  }

  public static void zipDirectory(String srcDir, String tgtZipfilethrows IOException {
    File directory = new File(srcDir);
    
    if (!directory.isDirectory()) {
      throw new IllegalArgumentException("No such directory :  " + srcDir);
    }
    
    System.out.println("Zipping directory : " + srcDir);
    
    /**
         * Create ZIP file
         */
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(tgtZipfile));
        zipDir(zipOut, directory);
        zipOut.close();
  }
  
  
  private static void zipDir(ZipOutputStream zipOut, File directory) {
      
      try {
        String [] filePaths = directory.list();
          FileInputStream fileInput = null;
          byte [] buf = new byte[1024];
          String entryName = null;
          int index = 0;
          File child = null;
          
          /**
           * Add each file as ZIP entry
           */
          for (int i = ; i < filePaths.length; i++) {
            child = new File(directory, filePaths[i]);
              entryName = child.getAbsolutePath();

              /**
               * Remove the drive prefix,
               
               * C:\NEW2\ABC   to NEW2\ABC
               * C:\NEW2\file_ops.txt   to NEW2\file_ops.txt
               * C:\NEW2\CCCC\AAA\IPC.LOG to NEW2\CCCC\AAA\IPC.LOG
               
               * If we don't remove the prefix, a directory
               * named C: is getting created in the ZIP file.
               * To avoid this remove the directory prefix.
               */
              index = entryName.indexOf(File.separator);
              if (index > 0) {
                entryName = entryName.substring(index + 1);
              }

              System.out.println("Adding : " + child.getAbsolutePath());
              
            /**
             * Zip child directory recursively
             */
            if (child.isDirectory()) {
                /**
                 * Add ZIP directory entry
                 */
              zipOut.putNextEntry(new ZipEntry(entryName + "/"));
              zipOut.closeEntry();
              
              /**
               * Iterate child directory
               */
              zipDir(zipOut, child);
            else {
              /**
               * Zip actual file content
               */
              fileInput = new FileInputStream(child);
                
                /**
                 * Add ZIP file entry
                 */
                zipOut.putNextEntry(new ZipEntry(entryName));
        
                /**
                 * Copy file content to ZIP stream
                 */
                int len;
                while ((len = fileInput.read(buf)) 0) {
                  zipOut.write(buf, 0, len);
                }
        
                fileInput.close();
                zipOut.closeEntry();
            }
          }
      
      catch (IOException e) {
        e.printStackTrace();
      }
  }
}
   

It gives the following output,
Zipping directory : C:\NEW2
Adding : C:\NEW2\AAA\abc.copy.txt
Adding : C:\NEW2\AAA\BIOSinfo.log
Adding : C:\NEW2\AAA\IPC.LOG
Adding : C:\NEW2\AAA\readonly_file.txt
Adding : C:\NEW2\AAA\software.tsv
Adding : C:\NEW2\abc.copy.txt
Adding : C:\NEW2\BIOSinfo.log
Adding : C:\NEW2\CCCC\AAA\abc.copy.txt
Adding : C:\NEW2\CCCC\AAA\BIOSinfo.log
Adding : C:\NEW2\CCCC\AAA\IPC.LOG
Adding : C:\NEW2\CCCC\AAA\readonly_file.txt
Adding : C:\NEW2\CCCC\AAA\software.tsv
Adding : C:\NEW2\CCCC\BIOSinfo.log
Adding : C:\NEW2\CCCC\IPC.LOG
Adding : C:\NEW2\CCCC\readonly_file.txt
Adding : C:\NEW2\file_ops.txt
Adding : C:\NEW2\IPC.LOG
Adding : C:\NEW2\NEW_SUB\BIOSinfo.log
Adding : C:\NEW2\NEW_SUB\IPC.LOG
Adding : C:\NEW2\NEW_SUB\readonly_file.txt
Adding : C:\NEW2\Oracle Identity Manager.txt
Adding : C:\NEW2\readonly_file.txt
Adding : C:\NEW2\software.tsv
Adding : C:\NEW2\test.txt
Done..



 
  


  
bl  br