gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:02:01 26 4
gpt4 key购买 nike

我有一个包含其他 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com