我有一个名为“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。
ZipFile
仅适用于......文件。 ZipEntry
只在记忆中,而不在硬盘上。
你最好使用ZipInputStream
:
FileInputStream
包裹成ZipInputStream
InputStream
InputStream
in到ZipInputStream
InputStream
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");
}
}
HTH!