Reputation: 389
I have a file named "file.ear". This file contains several files, including a "war" file, named "file.war" (which is also an archive). I intend to open a text file which is in "file.war". In this moment, my question is which is the best way to create a ZipFile object from this "file.war"
I created a ZipFile object from "file.ear" and iterated the entries. When the entry is "file.war" I tried to create another 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());
}
}
I expect to get a ZipFile instance from "file.war" and the line marked throws a FileNotFoundException.
Upvotes: 0
Views: 893
Reputation: 760
ZipFile
is only for ... files. A ZipEntry
is only in memory, not on the harddrive.
You're better off using ZipInputStream
:
FileInputStream
into a ZipInputStream
InputStream
InputStream
into a 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!
Upvotes: 1