tags:

views:

4477

answers:

5

Hi, I have zip file which contains some other zip files. For e.g. the mail file is abc.zip and it contains xyz.zip, class1.java, class2.java. And xyz.zip contains the file class3.java and class4.java.

So i need to extract the zip file using java to a folder that should contain class1.java, class2.java, class3.java and class4.java.

Thanks Anish

A: 

Here's algorithm for it

def unpackRecursive(filename):
    unpack file to temp dir

    while tempdir contain zip files:
        foreach zipfile in temp dir:
            unzip zipfile
            remove zipfile

    return files

I don't really know Java that well to code it, but this will work for sure. Maybe doing some voodoo with temporary directory so that it will be done in place would be a good idea.

Migol
A: 
File dir = new File("BASE DIRECTORY PATH");
FileFilter ff = new FileFilter() {

 @Override
 public boolean accept(File f) {
  //only want zip files
  return (f.isFile() && f.getName().toLowerCase().endsWith(".zip"));
 }
};

File[] list = null;
while ((list = dir.listFiles(ff)).length > 0) {
 File file1 = list[0];
 //TODO unzip the file to the base directory
}
Rickster
+4  A: 

Here's some untested code base on some old code I had that unzipped files.

public void doUnzip(String inputZip, String destinationDirectory)
        throws IOException {
    int BUFFER = 2048;
    List zipFiles = new ArrayList();
    File sourceZipFile = new File(inputZip);
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdir();

    ZipFile zipFile;
    // Open Zip file for reading
    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();

        File destFile = new File(unzipDestinationDirectory, currentEntry);
        destFile = new File(unzipDestinationDirectory, destFile.getName());

        if (currentEntry.endsWith(".zip")) {
            zipFiles.add(destFile.getAbsolutePath());
        }

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        try {
            // extract file if not a directory
            if (!entry.isDirectory()) {
                BufferedInputStream is =
                        new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dest =
                        new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
                fileCount++;
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    zipFile.close();

    for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
        String zipName = (String)iter.next();
        doUnzip(
            zipName,
            destinationDirectory +
                File.separatorChar +
                zipName.substr(0,zipName.lastIndexOf(".zip"))
        );
    }

}
Charlie
+2  A: 

I take ca.anderson4 and remove the List zipFiles and rewrite a little bit, this is what i got:

public class Unzip {

public void unzip(String zipFile) throws ZipException,
  IOException {

 System.out.println(zipFile);;
 int BUFFER = 2048;
 File file = new File(zipFile);

 ZipFile zip = new ZipFile(file);
 String newPath = zipFile.substring(0, zipFile.length() - 4);

 new File(newPath).mkdir();
 Enumeration zipFileEntries = zip.entries();

 // Process each entry
 while (zipFileEntries.hasMoreElements()) {
  // grab a zip file entry
  ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

  String currentEntry = entry.getName();

  File destFile = new File(newPath, currentEntry);
  destFile = new File(newPath, destFile.getName());
  File destinationParent = destFile.getParentFile();

  // create the parent directory structure if needed
  destinationParent.mkdirs();
  if (!entry.isDirectory()) {
   BufferedInputStream is = new BufferedInputStream(zip
     .getInputStream(entry));
   int currentByte;
   // establish buffer for writing file
   byte data[] = new byte[BUFFER];

   // write the current file to disk
   FileOutputStream fos = new FileOutputStream(destFile);
   BufferedOutputStream dest = new BufferedOutputStream(fos,
     BUFFER);

   // read and write until last byte is encountered
   while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
    dest.write(data, 0, currentByte);
   }
   dest.flush();
   dest.close();
   is.close();
  }
  if (currentEntry.endsWith(".zip")) {
   // found a zip file, try to open
   unzip(destFile.getAbsolutePath());
  }
 }
}

public static void main(String[] args) {
 Unzip unzipper=new Unzip();
 try {
  unzipper.unzip("test/test.zip");
 } catch (ZipException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}

}

I tested and it works

fero46
That code was actually written by ca.anderson4; I merely edited it (I don't like having to scroll side-to-side).
Michael Myers
aaa okey, I dont saw this :-). So i give credits to ca.anderson4 and the editor you ;-)
fero46
+1  A: 

In testing I noticed File.mkDirs() does not work under Windows...

/** * for a given full path name recreate all parent directories **/

 private void createParentHierarchy(String parentName) throws IOException {
  File parent = new File(parentName);
  String[] parentsStrArr = parent.getAbsolutePath().split(File.separator == "/" ? "/" : "\\\\");

  //create the parents of the parent
  for(int i=0; i < parentsStrArr.length; i++){
   StringBuffer currParentPath = new StringBuffer();
   for(int j = 0; j < i; j++){
    currParentPath.append(parentsStrArr[j]+File.separator);
   }
   File currParent = new File(currParentPath.toString());
   if(!currParent.isDirectory()){
    boolean created = currParent.mkdir();
    if(isVerbose)log("creating directory "+currParent.getAbsolutePath());
   }
  }

  //create the parent itself
  if(!parent.isDirectory()){
   boolean success = parent.mkdir();
  }
 }
boxymoron