在Java的zipentry中查找文件

5

我正在尝试在zip文件中查找一个文件,并将其作为InputStream获取。目前我所做的是这样的,但我不确定是否正确。

这是一个示例,原始内容稍长,但这是主要组成部分...

public InputStream Search_Image(String file_located, ZipInputStream zip) 
    throws IOException {
    for (ZipEntry zip_e = zip.getNextEntry(); zip_e != null ; zip_e = zip.getNextEntry()) {
        if (file_located.equals(zip_e.getName())) {
            return zip;
        }
        if (zip_e.isDirectory()) {
            Search_Image(file_located, zip); 
        }
    }
    return null;
}

我现在面临的主要问题是,Search_Image 中的 ZipInputStream 与原始组件的 ZipInputStream 相同...

if(zip_e.isDirectory()) {
    //"zip" is the same as the original I need a change here to find folders again.
    Search_Image(file_located, zip); 
}

现在的问题是,如何将ZipInputStream作为新的zip_entry获取?如果我的方法有任何问题,请纠正,因为我对这个类的逻辑仍然不太清楚。
3个回答

9

如果您暂时不需要输入流,请使用ZipFile类,无需烦恼。

ZipFile file = new ZipFile("file.zip");
ZipInputStream zis = searchImage("foo.png", file);

public InputStream searchImage(String name, ZipFile file) {
  for (ZipEntry e : Collections.list(file.entries())) {
    if (e.getName().endsWith(name)) {
      return file.getInputStream(e);
    }
  }
  return null;
}

一些事实:

  • 在您的代码中,应遵循命名方法和变量的惯例(例如,Search_Image 不好,应使用 searchImage
  • 压缩文件中的目录不包含任何文件,它们只是像其他所有条目一样的条目,因此您不应尝试递归到其中
  • 您应该使用 endsWith(name) 来比较您提供的名称,因为文件可能在文件夹内,而zip文件中的文件名始终包含路径

当我要查找的图像在一个带有压缩文件的文件夹中时会发生什么?我最初的方法是这样的,问题是它不会在目录中搜索图像。 - Donkey King
2
因为你使用了equals(..)而不是endsWith(..),请看一下我的第三点。 - Jack

5
使用ZipInputStream访问zip条目显然不是做这件事的方式,因为您需要迭代所有条目才能找到它,这是不可伸缩的方法,因为性能将取决于zip文件中的总条目数。要获得最佳性能,您需要使用ZipFile以便通过getEntry(name)方法直接访问一个条目,无论存档的大小如何。
public InputStream searchImage(String name, ZipFile zipFile) throws IOException {
    // Get the entry by its name
    ZipEntry entry = zipFile.getEntry(name);
    if (entry != null) {
        // The entry could be found
        return zipFile.getInputStream(entry);
    }
    // The entry could not be found
    return null;
}

请注意,在此处提供的名称是您图像在档案中的相对路径,使用/作为路径分隔符,因此如果您想访问位于目录bar中的foo.png,则预期的名称将是bar/foo.png

0

这是我的看法:

ZipFile zipFile = new ZipFile(new File("/path/to/zip/file.zip"));
InputStream inputStream = searchWithinZipArchive("findMe.txt", zipFile);

public InputStream searchWithinZipArchive(String name, ZipFile file) throws Exception {
  Enumeration<? extends ZipEntry> entries = file.entries();
  while(entries.hasMoreElements()){
     ZipEntry zipEntry = entries.nextElement();
      if(zipEntry.getName().toLowerCase().endsWith(name)){
             return file.getInputStream(zipEntry);
      }
  }
  return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接