首页 > 解决方案 > 使用 Java 打开另一个存档文件中的存档文件

问题描述

我有一个名为“file.ear”的文件。这个文件包含几个文件,包括一个名为“file.war”的“war”文件(它也是一个档案)。我打算打开一个位于“file.war”中的文本文件。在这一刻,我的问题是从这个“file.war”创建一个 ZipFile 对象的最佳方法是什么

我从“file.ear”创建了一个 ZipFile 对象并迭代了这些条目。当条目是“file.war”时,我尝试创建另一个 ZipFile

ZipFile earFile = new ZipFile("file.ear");
Enumeration(? extends ZipEntry) earEntries = earFile.entries();

while (earEntries.hasMoreElements()) {
    ZipEntry earEntry = earEntries.nextElement();
    if (earEntry.toString().equals("file.war")) {
        // in this line I want to get a ZipFile from the file "file.war"
        ZipFile warFile = new ZipFile(earEntry.toString());
    }
}

我希望从“file.war”中获得一个 ZipFile 实例,并且标记的行会引发 FileNotFoundException。

标签: javazipziparchive

解决方案


ZipFile仅适用于 ... 文件。AZipEntry只在内存中,不在硬盘上。

你最好使用ZipInputStream

  1. 你把你的包装FileInputStream成一个ZipInputStream
  2. 您可以保留 .war 条目InputStream
  3. 您将 .war 依次包装InputStreamZipInputStream
  4. 您可以保留文本文件条目,阅读其InputStream
  5. 对文本做任何你想做的事InputStream
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Snippet {

    public static void main(String[] args) throws IOException {

        InputStream w = getInputStreamForEntry(new FileInputStream("file.ear"), "file.war");
        InputStream t = getInputStreamForEntry(w, "prova.txt");

        try (Scanner s = new Scanner(t);) {
            s.useDelimiter("\\Z+");
            if (s.hasNext()) {
                System.out.println(s.next());
            }
        }

    }

    protected static InputStream getInputStreamForEntry(InputStream in, String entry)
            throws FileNotFoundException, IOException {
        ZipInputStream zis = new ZipInputStream(in);

        ZipEntry zipEntry = zis.getNextEntry();

        while (zipEntry != null) {
            if (zipEntry.toString().equals(entry)) {
                // in this line I want to get a ZipFile from the file "file.war"
                return zis;
            }
            zipEntry = zis.getNextEntry();
        }
        throw new IllegalStateException("No entry '" + entry + "' found in zip");
    }

}


推荐阅读