【问题标题】:How to read content of files inside Zip file which is inside a Zip file如何读取 Zip 文件中的 Zip 文件中的文件内容
【发布时间】:2019-10-09 16:50:06
【问题描述】:

邮编结构:-

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

【问题讨论】:

    标签: java zip


    【解决方案1】:
    ZipFile zip = new ZipFile("Outer.zip");
    ...
    zip.getInputStream(ze); // It is giving null
    

    ze 的内容(例如TxtFile1.txt)是InnerZip.zip 的一部分,而不是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) 否则我们将打印文件的内容(假设此处为文本文件)。

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      相关资源
      最近更新 更多