import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class ZipUtil {
public static void decompression(File zipPath, File dpath) throws Exception {
if (zipPath == null) {
throw new IllegalArgumentException("zipFile cannot be null");
}
if (!zipPath.isFile() && zipPath.exists()) {
throw new Exception("指定路径是目录或文件不存在:" + zipPath.getAbsolutePath());
}
String zipFileName = zipPath.getName();
if (zipFileName.toLowerCase().endsWith(".zip")) {
int nameLength = zipFileName.length();
zipFileName = zipFileName.substring(0, nameLength - 4);
}
if (dpath == null) {
dpath = new File(zipFileName);
} else {
dpath = new File(dpath, zipFileName);
}
if (dpath.exists()) {
System.out.println("目录已经存在:" + dpath.getAbsolutePath());
} else {
dpath.mkdirs();
}
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(
zipPath));
try {
ZipEntry entry = null;
ZipFile zipFile = new ZipFile(zipPath);
byte[] cache = new byte[8096];
while ((entry = zipInputStream.getNextEntry()) != null) {
String fileName = entry.getName();
if (entry.isDirectory()) {
new File(dpath, fileName).mkdirs();
continue;
}
InputStream inputStream = zipFile.getInputStream(entry);
OutputStream ops = null;
try {
// 创建文件,写文件
File tmpFile = new File(dpath, fileName);
tmpFile.createNewFile();
ops = new FileOutputStream(tmpFile);
int length = -1;
while ((length = inputStream.read(cache)) != -1) {
ops.write(cache, 0, length);
ops.flush();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (ops != null) {
ops.close();
}
zipInputStream.closeEntry();
}
}
} finally {
zipInputStream.close();
}
}
}
|