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();
}
}
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments