java 解压zip文件。
如果是文件夹的话会创建文件夹。
public static void unZip(String sourceZipDir, String targetDir) throws RuntimeException {
File sourceFile = new File(sourceZipDir);
final int BUFFER_SIZE = 1048576;
if (!sourceFile.exists()) {
throw new RuntimeException(sourceFile.getPath() + " is not exists.");
}
ZipFile zipFile = null;
try {
zipFile = new ZipFile(sourceFile);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
String dirPath = targetDir + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
File targetFile = new File(targetDir + "/" + entry.getName());
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
InputStream inputStream = zipFile.getInputStream(entry);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
int len;
byte[] buffer = new byte[BUFFER_SIZE];
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
}
}
} catch (Exception e) {
throw new RuntimeException("unzip error", e);
} finally {
if(zipFile != null){
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
参考:
https://www.cnblogs.com/wj123bk/p/16288621.html