如何在 Java 中将 zip 文件访问为 zip 文件

Sta*_*tan 4 java zip

我正在尝试读取位于 zip 文件中的 zip 文件本身的 .srt 文件。我成功地读取了 .srt 文件,这些文件位于一个简单的 zip 文件中,代码摘录如下:

    for (Enumeration enume = fis.entries(); enume.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) enume.nextElement();
                fileName = entry.toString().substring(0,entry.toString().length()-4);
try {
                    InputStream in = fis.getInputStream(entry);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String ext = entry.toString().substring(entry.toString().length()-4, entry.toString().length());
Run Code Online (Sandbox Code Playgroud)

但是现在我不知道如何访问 zip 文件中的 zip 文件。我尝试使用 ZipFile fis = new ZipFile(filePath) ,其中 filePath 是 zip 文件的路径 + 里面的 zip 文件的名称。它没有识别路径,所以我不知道我是否清楚。

谢谢。

Ian*_*rts 5

ZipFile仅适用于真实文件,因为它旨在用作随机访问机制,需要能够直接查找文件中的特定位置以按名称读取条目。但是正如 VGR 在评论中所建议的那样,虽然您无法随机访问 zip-inside-a-zip,但您可以使用ZipInputStream,它提供对条目的严格顺序访问并处理任何InputStreamzip 格式数据。

但是,ZipInputStream与其他流相比,使用模式有点奇怪 - 调用getNextEntry读取条目元数据并定位流以读取该条目的数据,您从该流读取,ZipInputStream直到它报告 EOF,然后您(可选)closeEntry()在移动到下一个条目之前调用在流中。

关键的一点是,你不能 close()ZipInputStream直到你读完的最后一项,所以这取决于你想与您可能需要使用类似的条目数据做什么的commons-io的CloseShieldInputStream防范越来越流过早关闭。

try(ZipInputStream outerZip = new ZipInputStream(fis)) {
  ZipEntry outerEntry = null;
  while((outerEntry = outerZip.getNextEntry()) != null) {
    if(outerEntry.getName().endsWith(".zip")) {
      try(ZipInputStream innerZip = new ZipInputStream(
                  new CloseShieldInputStream(outerZip))) {
        ZipEntry innerEntry = null;
        while((innerEntry = innerZip.getNextEntry()) != null) {
          if(innerEntry.getName().endsWith(".srt")) {
            // read the data from the innerZip stream
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)