How to decompress files from ZIP format using Java
decompress
unzip
zip
java
After we saw How to compress files in ZIP format using Java, here will see how to decompress files from ZIP format archive.
Example
package com.admfactory.io.archive;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipArchive {
public static void main(String[] args) {
String source = "D:\\admfactory.com\\archive.zip";
String output = "D:\\admfactory.com\\dir10\\";
System.out.println("UnZip Archive Example");
System.out.println();
System.out.println("Output to: " + output);
System.out.println();
unzip(source, output);
}
/**
* Zip the list received as parameter
*
* @param zipFile
* output ZIP file location
*/
public static void unzip(String zipFile, String output) {
byte[] buffer = new byte[1024];
try {
/** create output directory is not exists */
File folder = new File(output);
if (!folder.exists()) {
folder.mkdirs();
}
/** get the zip file content */
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
/** get the first zip file entry */
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(output + File.separator + fileName);
System.out.println("file unzip: " + newFile.getAbsolutePath());
/** create all non exists parent folders */
newFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
/** get the next zip file entry */
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println();
System.out.println("Done!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
UnZip Archive Example
Output to: D:\admfactory.com\dir10\
file unzip: D:\admfactory.com\dir10\dir3\dir4\f6.txt
file unzip: D:\admfactory.com\dir10\dir3\dir4\f7.txt
file unzip: D:\admfactory.com\dir10\dir3\f4.txt
file unzip: D:\admfactory.com\dir10\dir3\f5.txt
file unzip: D:\admfactory.com\dir10\f1.txt
file unzip: D:\admfactory.com\dir10\f2.txt
file unzip: D:\admfactory.com\dir10\f3.txt
Done!