zip ファイルのフォルダー内にある zip ファイルを持っています。zip 入力ストリームを使用してそれを読み取る方法を教えてください。
例えば:
abc.zip
|
documents/bcd.zip
zipファイル内のzipファイルを読み取る方法は?
zip ファイル内の zip ファイルを再帰的に調べたい場合は、
public void lookupSomethingInZip(InputStream fileInputStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
String entryName = "";
ZipEntry entry = zipInputStream.getNextEntry();
while (entry!=null) {
entryName = entry.getName();
if (entryName.endsWith("zip")) {
//recur if the entry is a zip file
lookupSomethingInZip(zipInputStream);
}
//do other operation with the entries..
entry=zipInputStream.getNextEntry();
}
}
ファイルから派生したファイル入力ストリームでメソッドを呼び出します -
File file = new File(name);
lookupSomethingInZip(new FileInputStream(file));
次のコード スニペットは、別の ZIP ファイル内の ZIP ファイルのエントリを一覧表示します。ニーズに合わせて調整してください。ボンネットの下にsZipFile
を使用します。ZipInputStream
コード スニペットは、具体的にはApache Commons IOIOUtils.copy
を使用しています。
public static void readInnerZipFile(File zipFile, String innerZipFileEntryName) {
ZipFile outerZipFile = null;
File tempFile = null;
FileOutputStream tempOut = null;
ZipFile innerZipFile = null;
try {
outerZipFile = new ZipFile(zipFile);
tempFile = File.createTempFile("tempFile", "zip");
tempOut = new FileOutputStream(tempFile);
IOUtils.copy( //
outerZipFile.getInputStream(new ZipEntry(innerZipFileEntryName)), //
tempOut);
innerZipFile = new ZipFile(tempFile);
Enumeration<? extends ZipEntry> entries = innerZipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
System.out.println(entry);
// InputStream entryIn = innerZipFile.getInputStream(entry);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Make sure to clean up your I/O streams
try {
if (outerZipFile != null)
outerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
IOUtils.closeQuietly(tempOut);
if (tempFile != null && !tempFile.delete()) {
System.out.println("Could not delete " + tempFile);
}
try {
if (innerZipFile != null)
innerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
readInnerZipFile(new File("abc.zip"), "documents/bcd.zip");
}