簡體   English   中英

打開 zip 存檔中的特定文件夾並迭代目錄結構

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

我們可以使用 python 確定 zip 存檔的文件夾結構如下(我們也可以在 Java 中執行相同的操作):

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

但是,是否可以確定 zip 存檔中特定文件夾的文件夾結構並僅遍歷該文件夾中的所有文件/文件夾(類似於路徑對象)? (而不是迭代 zip 存檔中的所有文件/文件夾,如前面的代碼示例所示)

您可以將文件讀取為 ZipFile,然后遍歷所有文件夾條目。 這是 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
  }
}

使用 Java NIO 將 ZIP 結構作為Path組件讀取非常簡單,因為FileSystems.newFileSystem(zip)文件系統的內置處理程序與其他 NIO 類一起使用,請參閱Files系統對象。

例如,這會掃描從文件夾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