首页 > 解决方案 > 如何读取 Zip 文件中的 Zip 文件中的文件内容

问题描述

邮编结构:-

OuterZip.zip--|
              |--Folder1---InnerZip.zip--|
                                         |--TxtFile1.txt    // Requirement is to read content of txt file 
                                         |--TxtFile2.txt    // Without extracting any of zip file

现在我可以读取 txt 文件的名称,但不能读取其中的内容。

代码:-

public static void main(String arg[]){
ZipFile zip = new ZipFile("Outer.zip");
ZipEntry ze;
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
    ZipEntry entry = (ZipEntry) e.nextElement();
    ZipInputStream zin = new ZipInputStream(zip.getInputStream(entry));
    while ((ze = zin.getNextEntry()) != null)
    {
        System.out.println(ze.getName());                                 //Can read names of txtfiles, Not contents
        zip.getInputStream(ze); // It is giving null
    }
}
}

PS:- 1. 想要在不提取文件系统中的任何 zip 的情况下执行此操作。
2. 已经在 SOF 上看到了一些答案。

标签: javazip

解决方案


ZipFile zip = new ZipFile("Outer.zip");
...
zip.getInputStream(ze); // It is giving null

ze(eg TxtFile1.txt) 的内容是InnerZip.zipnot的一部分Outer.zip(由 表示zip),因此null.

我会使用递归:

public static void main(String[] args) throws IOException {
     String name = "Outer.zip";
     FileInputStream input = new FileInputStream(new File(name));
     readZip(input, name);
}

public static void readZip(final InputStream in, final String name) throws IOException {
    final ZipInputStream zin = new ZipInputStream(in);
    ZipEntry entry;
    while ((entry = zin.getNextEntry()) != null) {
        if (entry.getName().toLowerCase().endsWith(".zip")) {
            readZip(zin, name + "/" + entry.getName());
        } else {
            readFile(zin, entry.getName());
        }
    }
}

private static void readFile(final InputStream in, final String name) {
    String contents = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
    System.out.println(String.format("Contents of %s: %s", name, contents));
}

0. while (...)我们正在遍历所有条目。

1. ( if (.endsWith(".zip"))) 如果遇到另一个 zip,我们会递归调用自身 ( readZip()) 并转到第0 步。

2. ( else) 否则我们打印文件的内容(假设这里是文本文件)。


推荐阅读