gpt4 book ai didi

java - 如何解压缩 zip 文件的特定目录中的所有文件?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:05 25 4
gpt4 key购买 nike

假设我有一个名为 Bundles.zip 的 .zip 文件,直接在 Bundles.zip 中,有几个文件和几个文件夹。这是 .zip 的样子:

Bundles.zip top level screenshot

现在,我想从 Bundles 文件夹中提取一切。我的程序已经知道需要从中提取文件的文件夹的名称,在本例中为 Bundles

zip 中的 Bundles 文件夹可以有文件、子文件夹、子文件夹中的文件,基本上任何东西,像这样:

Bundles.zip inner folder screenshot

我只需要将 Bundles 文件夹中的所有内容提取到输出目录即可。

如何在 Java 中完成此操作?我找到了解压缩 zip 中所有文件和文件夹的答案,但我只需要解压缩 zip 中的特定文件夹,而不是所有内容。

到目前为止的工作代码:

            ZipFile zipFile = new ZipFile(mapsDirectory + "mapUpload.tmp");
Enumeration zipEntries = zipFile.entries();
String fname;
String folderToExtract = "";
String originalFileNameNoExtension = originalFileName.replace(".zip", "");

while (zipEntries.hasMoreElements()) {
ZipEntry ze = ((ZipEntry)zipEntries.nextElement());

fname = ze.getName();

if (ze.isDirectory()) //if it is a folder
{

if(originalFileNameNoExtension.contains(fname)) //if this is the folder that I am searching for
{
folderToExtract = fname; //the name of the folder to extract all the files from is now fname
break;
}
}
}

if(folderToExtract == "")
{
printError(out, "Badly packaged Unturned map error: " + e.getMessage());
return;
}


//now, how do i extract everything from the folder named folderToExtract?

到目前为止的代码,originalFileName 类似于“The Island.zip”。在 zip 中有一个名为 The Island 的文件夹。我需要在 zip 文件中找到与 zip 文件名称匹配的文件夹,并提取其中的所有内容。

最佳答案

一种更简单的方法是使用 Java 7 的 NIO API。我刚刚为我的一个项目这样做了:

private void extractSubDir(URI zipFileUri, Path targetDir)
throws IOException {

FileSystem zipFs = FileSystems.newFileSystem(zipFileUri, new HashMap<>());
Path pathInZip = zipFs.getPath("path", "inside", "zip");
Files.walkFileTree(pathInZip, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
// Make sure that we conserve the hierachy of files and folders inside the zip
Path relativePathInZip = pathInZip.relativize(filePath);
Path targetPath = targetDir.resolve(relativePathInZip.toString());
Files.createDirectories(targetPath.getParent());

// And extract the file
Files.copy(filePath, targetPath);

return FileVisitResult.CONTINUE;
}
});
}

瞧。比使用 ZipFileZipEntry 干净得多,它还有一个额外的好处,即可以重复使用从任何类型的文件系统复制文件夹结构,而不仅仅是 zip 文件。

关于java - 如何解压缩 zip 文件的特定目录中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478765/

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