![](/img/trans.png)
[英]Copy a file into a double archive in Java (a zip file which is in another zip file)
[英]Open an archive file which is in another archive file using 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。
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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.