繁体   English   中英

如何读取 Zip 文件中的文件内容,该文件位于 Zip 文件中

[英]How to read content of files inside Zip file which is inside a Zip file

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 上看到了一些答案。

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

Contents of ze (eg TxtFile1.txt ) are part of InnerZip.zip not Outer.zip (represented by zip ), hence 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() ) 和 go 到步骤0。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM