我正在尝试从zip文件中读取提取给定文件。压缩文件也包含目录和子目录。我尝试了Java7 nio文件api,但是由于我的zip也包含子目录,因此我需要提供完整的路径来提取文件,这不适用于我的情况。因为我必须从用户那里提取文件来提取输入。我一直在尝试下面的代码,但是以某种方式读取ZipInputStream的方法不会读取任何要缓冲的内容。在调试时,我发现ZipInputStream对象的值在ZipInputStream中为空,这是因为其read方法仅返回-1。但是由于无法确定该值的设置方式,我现在陷入了困境。

try(OutputStream out=new FileOutputStream("filetoExtract");) {
    zipFile = new ZipFile("zipFile");
    Enumeration<? extends ZipEntry> e = zipFile.entries();
    while (e.hasMoreElements()) {
        ZipEntry entry = e.nextElement();
        if (!entry.isDirectory()) {
            String entryName = entry.getName();
            String fileName = entryName.substring(entryName.lastIndexOf("/") + 1);
            System.out.println(i++ + "." + entryName);
            if (searchFile.equalsIgnoreCase(fileName)) {
                System.out.println("File Found");
                BufferedInputStream bufferedInputStream = new BufferedInputStream(zipFile.getInputStream(entry));
                ZipInputStream zin = new ZipInputStream(bufferedInputStream);
                byte[] buffer = new byte[9000];
                int len;
                while ((len = zin.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                break;
            }
        }
    }
} catch (IOException ioe) {
    System.out.println("Error opening zip file" + ioe);
}


请在这里告诉我我做错了什么。谢谢

编辑:
经过调试后,我发现ZipFile类具有类似名称的内部类(ZipFileInputStream)。因此,它正在创建它的对象,而不是外部ZipFileInputStream类。所以我尝试了下面的代码,效果很好。但是我不太了解这里发生的事情。如果有人可以帮助我,那么幕后的逻辑真的很棒。

//  BufferedInputStream bufferedInputStream = new
//BufferedInputStream(zipFile.getInputStream(entry));
//ZipInputStream zin = new ZipInputStream(bufferedInputStream);
InputStream zin= zipFile.getInputStream(entry);

最佳答案

第二行是不必要的,因为zipFile.getInputStream(entry)已经返回表示解压缩数据的InputStream。因此,没有必要(或者实际上是错误的)将该InputStream包装在另一个ZipInputStream中:

BufferedInputStream bufferedInputStream = new BufferedInputStream(zipFile.getInputStream(entry));
ZipInputStream zin = new ZipInputStream(bufferedInputStream);

10-07 22:35