简体   繁体   English

打开 zip 存档中的特定文件夹并迭代目录结构

[英]Opening a particular folder inside the zip archive and iterate the directory structure

We can determine the folder structure of a zip archive using python as follows (we can do the same in Java also):我们可以使用 python 确定 zip 存档的文件夹结构如下(我们也可以在 Java 中执行相同的操作):

with zipfile.ZipFile('path to file', 'r') as zipobj:
    for item in zipobj.infolist():
        print(item.filename)

However, is it possible to determine the folder structure of a particular folder inside the zip archive and iterate through all files/folders inside that folder (similar to the path object) only?但是,是否可以确定 zip 存档中特定文件夹的文件夹结构并仅遍历该文件夹中的所有文件/文件夹(类似于路径对象)? (instead of iterating all files/folders inside the zip archive as shown in the previous code example) (而不是迭代 zip 存档中的所有文件/文件夹,如前面的代码示例所示)

You can read the file as ZipFile and then iterate over all the entries which are folders.您可以将文件读取为 ZipFile,然后遍历所有文件夹条目。 Here is a code snippet in Java:这是 Java 中的代码片段:

ZipFile zip = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
  ZipEntry entry = entries.nextElement();
  if (entry.isDirectory()) {
      // Code goes here
  }
}

Reading a ZIP structure as Path components is very simple with Java NIO as there are built in handlers for ZIP filesystems - see FileSystems.newFileSystem(zip) , and the Path objects it provides work with other NIO classes such as Files .使用 Java NIO 将 ZIP 结构作为Path组件读取非常简单,因为FileSystems.newFileSystem(zip)文件系统的内置处理程序与其他 NIO 类一起使用,请参阅Files系统对象。

For example this scans a zip starting from folder org/apache , and you can substitute any other filters needed treating the ZIP structure just like any other disc filesystem:例如,这会扫描从文件夹org/apache开始的 zip ,您可以替换处理 ZIP 结构所需的任何其他过滤器,就像任何其他磁盘文件系统一样:

try (FileSystem fs = FileSystems.newFileSystem(zip)) {
    Path root = fs.getPath("org/apache");
    try(Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, (p,a) -> true)) {
        stream.forEach(System.out::println);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM