gpt4 book ai didi

java - 使用 java.util.ZipFile 在同一层次结构中解压缩 zip 文件

转载 作者:行者123 更新时间:2023-12-02 07:49:06 27 4
gpt4 key购买 nike

给定一个具有多个嵌套目录结构的 zip 文件,我如何将它解压缩到相同的树结构中?ZipFile.entries() 是否以任何顺序提供枚举?

最佳答案

这是我的。

在文件中指定要展开的文件在目标目录中,您必须将目标位置指定为“new File("/tmp/foo/bar")”。如果你想在当前目录中解压,你可以指定 targetDir = new File(".")

public static void unzip(File file, File targetDir) throws ZipException,
IOException {
targetDir.mkdirs();
ZipFile zipFile = new ZipFile(file);
try {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File targetFile = new File(targetDir, entry.getName());
if (entry.isDirectory()) {
targetFile.mkdirs();
} else {
InputStream input = zipFile.getInputStream(entry);
try {
OutputStream output = new FileOutputStream(targetFile);
try {
copy(input, output);
} finally {
output.close();
}
} finally {
input.close();
}
}
}
} finally {
zipFile.close();
}
}

private static void copy(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[4096];
int size;
while ((size = input.read(buffer)) != -1)
output.write(buffer, 0, size);
}

为我工作。祝你好运。

关于java - 使用 java.util.ZipFile 在同一层次结构中解压缩 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4722049/

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