简体   繁体   中英

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):

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? (instead of iterating all files/folders inside the zip archive as shown in the previous code example)

You can read the file as ZipFile and then iterate over all the entries which are folders. Here is a code snippet in 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 .

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:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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