2012-06-01 56 views
2

說我有一個包含一個zip文件MyZipFile.zip(1)文件MyFile.txt和(2),其中包含一個文件MyFileInMyFolder.txt,即一些如下的文件夾MyFolder如何解壓縮有子目錄的zip文件?

MyZipFile.zip
    | - >MyFile.txt
    | - >MyFolder
                  | - >MyFileInMyFolder.txt

我想這個解壓縮zip歸檔。我一直能夠在網上找到的最常見的代碼示例使用ZipInputStream類,就像粘貼在這個問題底部的代碼一樣。然而,使用上述示例的問題是,它將創建MyFolder,但不會解壓縮MyFolder的內容。任何人都知道是否可以使用ZipInputStream或任何其他方式解壓縮zip壓縮文件夾中的文件夾的內容?

public static boolean unzip(File sourceZipFile, File targetFolder) 
{ 
// pre-stuff 

ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(sourceZipFile)); 
ZipEntry zipEntry = null; 

while ((zipEntry = zipInputStream.getNextEntry()) != null) 
{ 
    File zipEntryFile = new File(targetFolder, zipEntry.getName()); 

    if (zipEntry.isDirectory()) 
    { 
    if (!zipEntryFile.exists() && !zipEntryFile.mkdirs()) 
    return false; 
    } 
    else 
    { 
    FileOutputStream fileOutputStream = new FileOutputStream(zipEntryFile); 

    byte buffer[] = new byte[1024]; 
    int count; 

    while ((count = zipInputStream.read(buffer, 0, buffer.length)) != -1) 
    fileOutputStream.write(buffer, 0, count); 

    fileOutputStream.flush(); 
    fileOutputStream.close(); 
    zipInputStream.closeEntry(); 
    } 
} 

zipInputStream.close(); 

// post-stuff 
} 

回答

4

試試這個:

ZipInputStream zis = null; 
try { 

    zis = new ZipInputStream(new FileInputStream(zipFilePath)); 
    ZipEntry entry; 

    while ((entry = zis.getNextEntry()) != null) { 

     // Create a file on HDD in the destinationPath directory 
     // destinationPath is a "root" folder, where you want to extract your ZIP file 
     File entryFile = new File(destinationPath, entry.getName()); 
     if (entry.isDirectory()) { 

      if (entryFile.exists()) { 
       logger.log(Level.WARNING, "Directory {0} already exists!", entryFile); 
      } else { 
       entryFile.mkdirs(); 
      } 

     } else { 

      // Make sure all folders exists (they should, but the safer, the better ;-)) 
      if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) { 
       entryFile.getParentFile().mkdirs(); 
      } 

      // Create file on disk... 
      if (!entryFile.exists()) { 
       entryFile.createNewFile(); 
      } 

      // and rewrite data from stream 
      OutputStream os = null; 
      try { 
       os = new FileOutputStream(entryFile); 
       IOUtils.copy(zis, os); 
      } finally { 
       IOUtils.closeQuietly(os); 
      } 
     } 
    } 
} finally { 
    IOUtils.closeQuietly(zis); 
} 

注意,它使用Apache Commons IO來處理流複製/關閉。

+0

感謝您的迴應n。事實證明,我的代碼工作。問題是我的子文件夾(zip壓縮文件內)中的文件名以點(即'.MyFile.txt')開頭,儘管代碼運行正常(沒有例外等),但這些文件實際上並不是在解壓縮的目標文件夾中找到。我現在只是小心,不要讓我的文件名以點開頭。我確實包括了檢查'entryFile'父目錄是否存在的安全檢查(如果沒有,則創建它),謝謝。 –