'Read multiple files zip file with multiple sub directories
I have a zip file with the structure like: xml.zip
- Root Folder: package
- Folder: Subfolder.zip
- Inside Subfolder.zip :
- Root Folder: _
- Folder: var
- Folder: run
- Folder: xmls
- Xml1.xml
- Xml2.xml
- Folder: xmls
- Xml3.xml
- Folder: run
- Folder: var
- Root Folder: _
- Inside Subfolder.zip :
- Folder: Subfolder.zip
Is there a way to read in these three files recursively with the above structure? I've tried using ZipInputStream and ZipArchiveInputStream, but zip.getNextEntry() keeps returning null.. due to the nested zip. Anyway to recursively use it?
private void readZipFileStream(final InputStream zipFileStream) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry zipEntry;
try {
zipEntry = zipInputStream.getNextEntry();
while(zipEntry.getName() != null) {
System.out.println("name of zip entry: " + zipEntry.getName());
if (!zipEntry.isDirectory()) {
System.out.println("1."+zipInputStream.available());
System.out.println("2."+zipEntry.getName());
System.out.println("3."+zipEntry.isDirectory());
System.out.println("4."+zipEntry.getSize());
} else {
readZipFileStream(zipInputStream);
}
zipEntry = zipInputStream.getNextEntry();
}
// }
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help?
Solution 1:[1]
Started working after calling the same function again if getName().contains(".zip").
Solution 2:[2]
recursive call should be done when the zip entry is identified as zip file. Use zipEntry.getName().endsWith(".zip") to identify and then call the same function.
public static void readZip(InputStream fileStream) throws IOException
{
ZipInputStream zipStream = new ZipInputStream(fileStream);
ZipEntry zipEntry = zipStream.getNextEntry();
try {
while(zipEntry !=null) {
String fileName = zipEntry.getName();
if (fileName.endsWith(".zip")) {
//recur if the entry is a zip file
readZip(zipStream);
}
else {
System.out.println(zipEntry.getName());
}
zipEntry = zipStream.getNextEntry();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ayushie Saxena |
Solution 2 | Ruhul Hussain |