Created
June 27, 2012 06:44
-
-
Save musubu/3002043 to your computer and use it in GitHub Desktop.
Unzip in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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