在zipentry java中查找文件

在zipentry java中查找文件,java,zipinputstream,Java,Zipinputstream,我试图在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文件中找到一个文件,并将其作为
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\u 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\u条目
?另外,如果我在方法中做了任何错误,请添加,因为我对该类的逻辑仍然不足。

如果不需要,您应该使用该类
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\u Image
    不好,
    searchImage
    好)
  • zip文件中的目录不包含任何文件,它们与其他文件一样只是条目,因此您不应该尝试递归到它们中)
  • 您应该使用
    endsWith(name)
    比较您提供的名称,因为文件可能位于文件夹中,而zip中的文件名始终包含路径

使用
ZipInputStream
访问zip条目显然不是这样做的,因为您需要迭代条目以找到它,这不是一种可伸缩的方法,因为性能将取决于zip文件中条目的总量

为了获得尽可能好的性能,您需要使用,以便直接访问条目,无论归档文件大小如何

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
,以下是我的看法:

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;
}
ZipFile-ZipFile=new-ZipFile(新文件(“/path/to/zip/File.zip”);
InputStream InputStream=searchWithinZipArchive(“findMe.txt”,zipFile);
公共InputStream searchWithinZipArchive(字符串名称,ZipFile文件)引发异常{

枚举当我搜索的图像位于带有zip?的文件夹中时会发生什么情况。我最初的方法是这样做的,问题是这不会搜索图像的目录。因为您使用的是
equals(..)
,而不是
endsWith(..)
,请查看我的第三点。