2009-06-11 13 views
29

Ho un file zip che contiene alcuni altri file zip. Ad es. il file di posta è abc.zip e contiene xyz.zip, class1.java, class2.java. E xyz.zip contiene il file class3.java e class4.java.Come decomprimere i file ricorsivamente in Java?

Quindi ho bisogno di estrarre il file zip usando java in una cartella che dovrebbe contenere class1.java, class2.java, class3.java e class4.java.

+0

Questo sarà davvero pasticcio su questo t chiedere: http://aioobe.org/zip-quine/. (Zip infinito ricorsivo in una cerniera in-a-..) – GKFX

+0

Solo un pensiero, tutte le risposte qui presentate non funzionano in realtà perché non hai considerato le zip annidate – ha9u63ar

risposta

-2
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 
} 
9

Ecco alcune basi di codice non testate su un vecchio codice che avevo i file decompressi.

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(); 
      } 
     } 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.substring(0,zipName.lastIndexOf(".zip")) 
     ); 
    } 

} 
+0

Perché tu avere una dichiarazione di tiri, eppure in realtà cattura l'eccezione e la registra? Non significa che i chiamanti si aspettano IOExceptions che non vengono mai lanciati ..? –

+0

Grazie per aver fornito questo, molto utile! –

+0

Il codice piacevole ha apportato alcune modifiche e funziona bene grazie – GFlam

5

prendo ca.anderson4 e rimuovere i file zip List e riscrivere un po ', questo è quello che ho ottenuto:

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(); 
    } 
} 

} 

ho provato e funziona

+0

Questo codice è stato effettivamente scritto da ca.anderson4; L'ho semplicemente modificato (non mi piace dover scorrere da lato a lato). –

+0

aaa okey, non ho visto questo :-). Quindi do i crediti a ca.anderson4 e l'editor a te ;-) – fero46

+0

Questo semplicemente scarica tutti i file in tutte le sottocartelle in una cartella, distruggendo così l'intera struttura dell'archivio – Ibolit

2

Nei test ho notato File .mkDirs() non funziona sotto Windows ...

/** * per un dato percorso completo ricreare tutte le directory principali **/

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(); 
     } 
    } 
64

Questa soluzione è molto simile alle precedenti soluzioni già postato, ma questo ricrea la struttura delle cartelle adeguata su Unzip.

static public void extractFolder(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 
      extractFolder(destFile.getAbsolutePath()); 
     } 
    } 
} 
+1

Questa funzione mi ha salvato la vita. Alcune funzioni zip pre-scritte nel nostro progetto non erano semplicemente in grado di estrarre le cartelle all'interno del file. Funziona alla grande Grazie mille per la condivisione. – kingsmasher1

+1

Sono sorpreso di come questa risposta non sia stata accettata. Ad ogni modo, upvote per te e grazie ancora. – kingsmasher1

+0

Grazie, questo ha funzionato immediatamente per me. –

0

Stessa risposta di NeilMonday, ma estratti directory vuote:

static public void extractFolder(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(); 
     } 
     else{ 
      destFile.mkdirs() 
     } 
     if (currentEntry.endsWith(".zip")) 
     { 
      // found a zip file, try to open 
      extractFolder(destFile.getAbsolutePath()); 
     } 
    } 
} 
1

Si dovrebbe chiudere il file zip dopo Unzip.

static public void extractFolder(String zipFile) throws ZipException, IOException 
{ 
    System.out.println(zipFile); 
    int BUFFER = 2048; 
    File file = new File(zipFile); 

    ZipFile zip = new ZipFile(file); 
    try 
    { 
     ...code from other answers (ex. NeilMonday)... 
    } 
    finally 
    { 
     zip.close(); 
    } 
} 
1

modificato come avevo bisogno poi mescolati in un po 'delle migliori risposte. Questa versione:

  • ricorsivamente estrarre una zip determinato luogo

  • Creare directory vuote

  • chiudere zip correttamente


public static void unZipAll(File source, File destination) throws IOException 
{ 
    System.out.println("Unzipping - " + source.getName()); 
    int BUFFER = 2048; 

    ZipFile zip = new ZipFile(source); 
    try{ 
     destination.getParentFile().mkdirs(); 
     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(destination, 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 = null; 
       FileOutputStream fos = null; 
       BufferedOutputStream dest = null; 
       try{ 
        is = new BufferedInputStream(zip.getInputStream(entry)); 
        int currentByte; 
        // establish buffer for writing file 
        byte data[] = new byte[BUFFER]; 

        // write the current file to disk 
        fos = new FileOutputStream(destFile); 
        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); 
        } 
       } catch (Exception e){ 
        System.out.println("unable to extract entry:" + entry.getName()); 
        throw e; 
       } finally{ 
        if (dest != null){ 
         dest.close(); 
        } 
        if (fos != null){ 
         fos.close(); 
        } 
        if (is != null){ 
         is.close(); 
        } 
       } 
      }else{ 
       //Create directory 
       destFile.mkdirs(); 
      } 

      if (currentEntry.endsWith(".zip")) 
      { 
       // found a zip file, try to extract 
       unZipAll(destFile, destinationParent); 
       if(!destFile.delete()){ 
        System.out.println("Could not delete zip"); 
       } 
      } 
     } 
    } catch(Exception e){ 
     e.printStackTrace(); 
     System.out.println("Failed to successfully unzip:" + source.getName()); 
    } finally { 
     zip.close(); 
    } 
    System.out.println("Done Unzipping:" + source.getName()); 
} 
Problemi correlati