如何解压缩具有子目录的zip存档?

时间:2012-06-01 11:22:26

标签: java android

假设我有一个zip文件MyZipFile.zip,其中包含(1)文件MyFile.txt和(2)包含文件MyFolder的文件夹MyFileInMyFolder.txt,即如下:

  

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
}

1 个答案:

答案 0 :(得分: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来处理流复制/关闭。