gpt4 book ai didi

Java从zip文件中获取顶级文件夹

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

我有点陷入这个问题。我只想打印 zip 文件中的顶级目录。例如,我有一个具有以下结构的 zip 文件:

Sample.zip
- sound
- game
-start.wav
-end.wav
- Intro
- custom
- Scene
- fight
- Angle
..............

上图显示:Sample.zip有2个文件夹(sound和custom),sound里面有2个文件夹game和Intro等等...

现在我知道如何打开并从 zip 文件中获取目录:例如(工作代码)

try {
appFile = ("../../Sample.zip"); // just the path to zip file
ZipFile zipFile = new ZipFile(appFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if(entry.isDirectory()){
String dir = entry.getName();
File file = new File(dir);
System.out.println(file.getParent());
}
}
} catch (IOException e) {
System.out.println("Error opening Zip" +e);
}

现在我也知道我可以使用 .getParent()(如您在上面看到的)来获取顶级目录,但是上面的实现没有奏效。它会列出所有目录,例如

 null   
sound
game
null
custom
scene
Angle

我的问题是如何才能真正打印顶级文件夹,在上面的场景中,soundcustom

如有任何提示,我将不胜感激。

最佳答案

实际上,我按照@JB Nizet 的建议进行了操作并解决了问题(它确实有效):

try {
appFile = ("../../Sample.zip"); // just the path to zip file
ZipFile zipFile = new ZipFile(appFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if(entry.isDirectory()){
File file = new File(entry.getName());
if(file.getParent() == null){
System.out.println(file.getName());
}
}
}
} catch (IOException e) {
System.out.println("Error opening Zip" +e);
}

上述解决方案有效,因为顶级目录没有父目录,因此返回 null 作为输出。所以我只是循环目录以查看它们是否有父目录,如果它们没有任何父目录,那么它们就是顶级目录。

关于Java从zip文件中获取顶级文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29303455/

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