Here's a generic handling of an entire zip file. It processes each file at the byte level, so you can get at text files, as well binary (images, PDF's, etc.) files. This code unzips the entire zip file, creating and including any subdirectories it encounters along the way.
- The
zipFilePath
is the zip file pathname as a string.
- The
unzipPath
is the unzip pathname as a string.
function unzipFile(zipFilePath, unzipPath) {
var zipFile = null;
try {
zipFile = new java.util.zip.ZipFile(zipFilePath);
var entries = zipFile.entries();
var bytes = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024);
while (entries.hasMoreElements()) {
var zipEntry = new java.util.zip.ZipEntry(entries.nextElement());
var fileFromZipEntry = new java.io.File(unzipPath + java.io.File.separator + zipEntry.getName());
//zipEntry reports / as separator, even on Windows, so we're not using java.io.File.separator in the following test
if (StringUtils.endsWith(zipEntry.getName(), '/')) {
fileFromZipEntry.mkdirs();
continue;
} else {
var inputStream = null;
var outputStream = null;
var length = -1;
try {
inputStream = zipFile.getInputStream(zipEntry);
outputStream = new java.io.FileOutputStream(fileFromZipEntry);
while ((length = inputStream.read(bytes)) >= 0) {
outputStream.write(bytes, 0, length);
}
} finally {
if (inputStream !== null) {
inputStream.close();
inputStream = null;
}
if (outputStream !== null) {
outputStream.close();
outputStream = null;
}
}
}
}
} catch (err) {
qie.error('Failed to unzip file \'' + zipFilePath + '\': ' + err);
} finally {
if (zipFile !== null) {
zipFile.close();
zipFile = null;
}
}
}
A sample call to this function would look like:
unzipFile('c:\\temp\\compressed\\myZipFile.zip', 'c:\\temp\\decompressed\\myZipFile');