Reputation: 1645
I am creating a method in Java to open a zipfile and process Excel files in the zip dynamically. I am using the API ZipFile in Java and would like to process the zipfile as is in memory without extracting it to the file system.
So far I am able to iterate through the zip file but am having trouble listing the files underneath a directory in the zip file. Excel files can be in a folder in the zip file. Below is my current code with a comment in the section that I am having trouble with. Any help is greatly appreciated :)
public static void main(String[] args) {
try {
ZipFile zip = new ZipFile(new File("C:\\sample.zip"));
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
String currentEntry = entry.getName();
if (entry.isDirectory()) {
/*I do not know how to get the files underneath the directory
so that I can process them */
InputStream is = zip.getInputStream(entry);
} else {
InputStream is = zip.getInputStream(entry);
}
}
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 5
Views: 8808
Reputation: 347204
Zip entries don't actually have any concept about folders or directories, they all exist within the same conceptual root within the zip file. The thing that allows files to organised into "folders" is the name of the zip entry.
A zip entry is considered a directory only because it doesn't actually contain any compressed bytes and is flagged as such.
The directory entry is a mark to allow you the opportunity to construct the path to which files using the same path prefix need to be extracted to.
This means, you don't need to really care about the directory entries, other then prehaps create the output folder any following files might need
Upvotes: 5
Reputation: 21978
Please take a look on here and here
public static void unzip(final ZipFile zipfile, final File directory)
throws IOException {
final Enumeration<? extends ZipEntry> entries = zipfile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final File file = file(directory, entry);
if (entry.isDirectory()) {
continue;
}
final InputStream input = zipfile.getInputStream(entry);
try {
// copy bytes from input to file
} finally {
input.close();
}
}
}
protected static File file(final File root, final ZipEntry entry)
throws IOException {
final File file = new File(root, entry.getName());
File parent = file;
if (!entry.isDirectory()) {
final String name = entry.getName();
final int index = name.lastIndexOf('/');
if (index != -1) {
parent = new File(root, name.substring(0, index));
}
}
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
throw new IOException(
"failed to create a directory: " + parent.getPath());
}
return file;
}
Upvotes: 3