一、注意事项
1.本文是一个解压与压缩的工具类,读者可以直接拷贝到工程里进行测试
2.本文代码所有异常全部抛出,读者可自行修改
3.关闭流时候一定注意关闭顺序,先创建的流后关闭
4.有什么不足之处,欢迎大家指正
二、代码
package com.xxx.zip;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;
public class ZipUtil {
public static void zip(File inFile, File outFile) throws IOException {
//创建文件输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
//压缩文件时生成校验和 保证数据一致性
CheckedOutputStream cos = new CheckedOutputStream(bos, new Adler32());
//创建ZipOutputStream流
ZipOutputStream zos = new ZipOutputStream(cos);
String rootPath = "";
if (inFile.isDirectory()) {//判断输入的路径是目录还是文件 方便后续处理
rootPath = inFile.getName();//赋值为当前目录名 方面后续路径截取
}
if (rootPath == "") {//文件的压缩方法
zipFile(inFile, zos);
} else { //目录的压缩方法
zipFile(inFile, zos, rootPath);
}
//关闭流 注意关闭顺序 否则压缩后的文件有问题
zos.close();
cos.close();
bos.close();
}
private static void zipFile(File inFile, ZipOutputStream zos, String rootPath) throws IOException {
if (inFile.isDirectory()) { //如果为目录
zos.putNextEntry(new ZipEntry(inFile.getPath().substring(inFile.getPath().indexOf(rootPath)) + File.separator));
for (File file : inFile.listFiles()) {
zipFile(file, zos, rootPath);
}
} else { //如果是文件
System.out.println("正在压缩文件:" + inFile.getName());
zos.putNextEntry(new ZipEntry(inFile.getPath().substring(inFile.getPath().indexOf(rootPath))));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFile));
int len = 0;
byte[] b = new byte[1024];
while ((len = bis.read(b)) > 0) {
zos.write(b, 0, len);
}
zos.closeEntry();
bis.close();
}
}
private static void zipFile(File inFile, ZipOutputStream zos) throws IOException {
System.out.println("正在压缩文件:" + inFile.getName());
zos.putNextEntry(new ZipEntry(inFile.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFile));
int len = 0;
byte[] b = new byte[1024];
while ((len = bis.read(b)) > 0) {
zos.write(b, 0, len);
}
zos.closeEntry();
bis.close();
}
public static void unZipFile(String zipPath, String outPath) throws IOException {
ZipFile zipFile = new ZipFile(zipPath);//创建ZipFile
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
if (!zipEntry.getName().endsWith(File.pathSeparator)) {
System.out.println("正在解压文件:" + zipEntry.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath + zipEntry.getName()));
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
CheckedInputStream cis = new CheckedInputStream(bis, new Adler32());
int len = 0;
byte[] b = new byte[1024];
while ((len = cis.read(b)) > 0) {
bos.write(b, 0, len);
}
cis.close();
bis.close();
bos.close();
} else {
new File(outPath + zipEntry.getName()).mkdirs();
}
}
zipFile.close();
System.out.println("解压完成");
}
}