java - 如何在Java中递归解压缩文件?

标签 java unzip

我有一个包含其他 zip 文件的 zip 文件。

例如,邮件文件是abc.zip,它包含xyz.zipclass1.javaclass2。 java 。而 xyz.zip 包含文件 class3.javaclass4.java

所以我需要使用 Java 将 zip 文件提取到应包含 class1.javaclass2.javaclass3.java 的文件夹中> 和 class4.java.

最佳答案

警告,此处的代码适用于受信任的 zip 文件,写入前没有路径验证,这可能导致安全漏洞,如 zip-slip-vulnerability 中所述如果您使用它来压缩来自未知客户端的上传 zip 文件。


此解决方案与之前发布的解决方案非常相似,但此解决方案在解压缩时重新创建了正确的文件夹结构。

public static void extractFolder(String zipFile) throws IOException {
int buffer = 2048;
File file = new File(zipFile);

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

  new File(newPath).mkdir();
  Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

  // Process each entry
  while (zipFileEntries.hasMoreElements()) {
    // grab a zip file entry
    ZipEntry entry = zipFileEntries.nextElement();
    String currentEntry = entry.getName();
    File destFile = new File(newPath, currentEntry);
    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);
      try (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();
        is.close();
      }
    }

    if (currentEntry.endsWith(".zip")) {
      // found a zip file, try to open
      extractFolder(destFile.getAbsolutePath());
    }
  }
}

}

关于java - 如何在Java中递归解压缩文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/981578/

相关文章:

java - 在 SQL 中更新查询,在 Java 上运行时出现语法错误

java - 将对象分配给数组

java - 如何在 WebView 中禁用软键盘

java - Selenium 无法在找到的元素中发送键

asp-classic - 在经典 asp 中解压缩文件

java - 应用程序在 Debug模式下运行顺利,但在 Release模式下崩溃

python - 如何使用 python 将流上传到 AWS s3

php - 需要 PHP 脚本来解压和循环压缩文件

c# - Shell32.dll 引用导致问题

c++ - 使用 zlib 解压缩 .zip 文件的简单方法