四处收集的代码
运行效率: 方法一 > 方法二
测试数据不大只有100M,方法一至少比方法二快3~4倍
/**
* 解压实现
*
* @param srcZipFile 输入的压缩文件
* @param basePath 解压文件存放的父路径
*/
private static void unpackOne(File srcZipFile,String basePath) {
try {
ZipFile zipFile = new ZipFile(srcZipFile);
Enumeration entries = zipFile.entries();
//迭代枚举
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
//输出路径
String outPath = basePath + File.separatorChar + zipEntry.getName();
outPath = outPath.replace('\\', '/').replace('/', File.separatorChar);
//创建父文件(关键),因为可能会出现像这样的情况"D:/文件夹/",导致无法找到父路径
File parentFile = new File(outPath.substring(0, outPath.lastIndexOf(File.separatorChar)));
// 判断父路径是否存在,不存在则创建文件路径
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是,不需要解压
File outFile = new File(outPath);
if (outFile.isDirectory()) {
if (!outFile.exists()) {
outFile.mkdirs();
}
continue;
}
//解压
try (InputStream in = zipFile.getInputStream(zipEntry);
BufferedInputStream bis = new BufferedInputStream(in);
FileOutputStream fos = new FileOutputStream(outFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
outputData(bis, bos);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解压实现
*
* @param srcZipFile 输入的压缩文件
* @param basePath 解压文件存放的父路径
*/
private static void unpackTwo(File srcZipFile,String basePath) {
try (FileInputStream fis = new FileInputStream(srcZipFile);
ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
//输出路径
String outPath = basePath + File.separator + zipEntry.getName();
outPath = outPath.replace('\\', '/').replace('/', File.separatorChar);
//创建父文件(关键),因为可能会出现像这样的情况"D:/文件夹/",导致无法找到父路径
File parentFile = new File(outPath.substring(0, outPath.lastIndexOf(File.separatorChar)));
// 判断父路径是否存在,不存在则创建文件路径
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是,不需要解压
File outFile = new File(outPath);
if (outFile.isDirectory()) {
if (!outFile.exists()) {
outFile.mkdirs();
}
continue;
}
//解压
try (FileOutputStream fos = new FileOutputStream(outFile);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
outputData(zis, bos);
}
zis.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 把字节输入流数据写给输出流(或内存)
*
* @param inputStream 字节输入流
* @param outputStream 字节输出流
*/
public static void outputData(InputStream inputStream,
OutputStream outputStream) {
try {
byte[] bytes = new byte[4096];
int length;
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}