Pra*_*rri 8 java zip file unzip
我有zip文件在zip文件的文件夹里面,请建议我如何使用zip输入流阅读它.
例如:
abc.zip
|
documents/bcd.zip
Run Code Online (Sandbox Code Playgroud)
如何在zip文件中读取zip文件?
小智 6
如果你想以递归方式查看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();
}
}
Run Code Online (Sandbox Code Playgroud)
使用从文件派生的文件输入流调用方法 -
File file = new File(name);
lookupSomethingInZip(new FileInputStream(file));
Run Code Online (Sandbox Code Playgroud)
以下代码段列出了另一个ZIP文件中ZIP文件的条目.根据您的需求进行调整.在引擎盖下ZipFile使用ZipInputStreams.
所述代码段使用Apache的百科全书IO,具体IOUtils.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");
}
Run Code Online (Sandbox Code Playgroud)