Skip to content

Instantly share code, notes, and snippets.

@musubu
Created June 27, 2012 06:44
Show Gist options
  • Save musubu/3002043 to your computer and use it in GitHub Desktop.
Save musubu/3002043 to your computer and use it in GitHub Desktop.
Unzip in Java
package utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Zip utilities
*
* @author Musubu Inc.
*/
public class ZipUtils {
/**
* Unzip a zip file
*
* @param file
* @param parentDirectoryPath
* @throws IOException
*/
public static void unzip(File file, String parentDirectoryPath) throws IOException {
if (!StringUtils.isEmpty(parentDirectoryPath)) {
File parentDirectory = new File(parentDirectoryPath);
if (!parentDirectory.exists()) {
parentDirectory.mkdirs();
}
parentDirectoryPath = parentDirectoryPath + "/";
}
ZipFile zipFile = new ZipFile(file);
Enumeration enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
if (zipEntry.isDirectory()) {
new File(parentDirectoryPath + zipEntry.getName()).mkdirs();
} else {
File parent = new File(parentDirectoryPath + zipEntry.getName()).getParentFile();
if (parent != null) parent.mkdirs();
FileOutputStream fileOutputStream = new FileOutputStream(parentDirectoryPath + zipEntry.getName());
InputStream inputStream = zipFile.getInputStream(zipEntry);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, size);
}
fileOutputStream.close();
}
}
}
/**
* Unzip a zip file
*
* @param file
* @param parentDirectory
* @throws IOException
*/
public static void unzip(File file, File parentDirectory) throws IOException {
String parentDirectoryPath = parentDirectory.getAbsolutePath();
unzip(file, parentDirectoryPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment