2

假设我有一个 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
}
4

1 回答 1

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来处理流复制/关闭。

于 2012-06-01T13:24:01.067 回答