问题描述
我的zip文件包含其他一些zip文件。
I have zip file which contains some other zip files.
例如,邮件文件是 abc.zip
它包含 xyz.zip
, class1.java
, class2.java
。并且 xyz.zip
包含文件 class3.java
和 class4.java
。
For example, the mail file is abc.zip
and it contains xyz.zip
, class1.java
, class2.java
. And xyz.zip
contains the file class3.java
and class4.java
.
所以我需要使用Java将zip文件解压缩到一个文件夹,该文件夹应该包含 class1.java
, class2.java
, class3.java
和 class4.java
。
So I need to extract the zip file using Java to a folder that should contain class1.java
, class2.java
, class3.java
and class4.java
.
推荐答案
警告,这里的代码对于可信的zip文件是可以的,在写入之前没有路径验证可能导致安全漏洞,如中所述,如果您使用它来收集上传的内容来自未知客户端的zip文件。
Warning, the code here is ok for trusted zip files, there's no path validation before write which may lead to security vulnerability as described in zip-slip-vulnerability if you use it to deflate an uploaded zip file from unknown client.
此解决方案与之前发布的解决方案非常相似,但是这个解决方案重新创建了正确的解决方案解压缩时的文件夹结构。
This solution is very similar to the previous solutions already posted, but this one recreates the proper folder structure on unzip.
static public void extractFolder(String zipFile) throws ZipException, IOException
{
System.out.println(zipFile);
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = zipFile.substring(0, zipFile.length() - 4);
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
//destFile = new File(newPath, destFile.getName());
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);
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();
dest.close();
is.close();
}
if (currentEntry.endsWith(".zip"))
{
// found a zip file, try to open
extractFolder(destFile.getAbsolutePath());
}
}
}
这篇关于如何在Java中递归解压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!