我有一个名为“ 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。
答案 0 :(得分:1)
ZipFile
仅适用于...文件。 ZipEntry
仅在内存中,而不在硬盘驱动器上。
最好使用ZipInputStream
:
FileInputStream
包裹到ZipInputStream
InputStream
InputStream
包装成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!