我有一个包含其他 zip 文件的 zip 文件。
例如,邮件文件是abc.zip
,它包含xyz.zip
、class1.java
、class2。 java
。而 xyz.zip
包含文件 class3.java
和 class4.java
。
所以我需要使用 Java 将 zip 文件提取到应包含 class1.java
、class2.java
、class3.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/