有没有什么示例代码,如何将ZIP中的文件夹解压到我想要的目录中?我已经将文件夹" folder“中的所有文件读取到字节数组中,如何从其文件结构重新创建?
发布于 2013-04-12 19:10:31
我不确定你说的具体是什么意思?你的意思是没有API帮助的情况下自己做吗?
如果你不介意使用一些开源库,有一个很酷的API,叫做
zip4J
它很容易使用,我认为有很好的反馈。请参阅此示例:
String source = "folder/source.zip";
String destination = "folder/source/";
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
如果你想解压的文件有密码,你可以尝试这样做:
String source = "folder/source.zip";
String destination = "folder/source/";
String password = "password";
try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
我希望这是有用的。
发布于 2012-05-17 19:06:59
这是我使用的代码。更改缓冲区
_
尺寸满足您的需求。
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public final class ZipUtils {
private static final int BUFFER_SIZE = 4096;
public static void extract(ZipInputStream zip, File target) throws IOException {
try {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
File file = new File(target, entry.getName());
if (!file.toPath().normalize().startsWith(target.toPath())) {
throw new IOException("Bad zip entry");
}
if (entry.isDirectory()) {
file.mkdirs();
continue;
}
byte[] buffer = new byte[BUFFER_SIZE];
file.getParentFile().mkdirs();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
int count;
while ((count = zip.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
}
} finally {
zip.close();
}
}
}
发布于 2020-01-04 00:21:01
这是一个最简洁的、无库的Java 7+变体:
public static void unzip(InputStream is, Path targetDir) throws IOException {
targetDir = targetDir.toAbsolutePath();
try (ZipInputStream zipIn = new ZipInputStream(is)) {
for (ZipEntry ze; (ze = zipIn.getNextEntry()) != null; ) {
Path resolvedPath = targetDir.resolve(ze.getName()).normalize();
if (!resolvedPath.startsWith(targetDir)) {
// see: https://snyk.io/research/zip-slip-vulnerability
throw new RuntimeException("Entry with an illegal path: "
+ ze.getName());
}
if (ze.isDirectory()) {
Files.createDirectories(resolvedPath);
} else {
Files.createDirectories(resolvedPath.getParent());
Files.copy(zipIn, resolvedPath);
}
}
}
}
The The The
在两个分支中都需要,因为zip文件并不总是包含所有父目录作为单独的条目,而可能只是为了表示空目录而包含它们。
这段代码解决了
ZIP-slip漏洞
,则它将失败。如果某些ZIP条目位于
..。这样的压缩不是使用常用工具创建的,很可能是手工创建的,以利用漏洞进行攻击。
https://stackoverflow.com/questions/10633595
复制相似问题