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

标签 java file zip directory

我有点陷入这个问题。我只想打印 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/

相关文章:

java - 如何检查登录信息是否与文件中的记录相对应? ( socket )

java - 如何将 .wav 文件转换为字节数组?

java - 压缩文件的 MD5 散列

php - 将文件添加到存档后删除文件会阻止创建存档

java - 将特定变量从文本文件输出到控制台Java

java - 如何在 Java 中从字符串设置字体

java - Netbeans 和重构

java - 如何为 Java 程序创建 .exe?

java - 文件显然无法转换为文件

java - 在 Java 中,您可以浏览嵌套 zip 文件的内容而不膨胀父文件吗?