Java实现zip压缩(支持空文件夹)
当文件中含有文件以及文件夹(空文件夹)时同样适用
/**
* 文件压缩
*
* @param src 文件源目录
* @param des 压缩文件路径
* @return
* @author
* date 2019-07-26
**/
public static void fileZip(String src, String des) {
File srcPath = new File(src);
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(new File(des)));
compress(srcPath, out, "");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
对文件进行压缩
private static void compress(File srcPath, ZipOutputStream out, String base) throws Exception {
//判断是否是目录 取出所有目录下的所有文件
if (srcPath.isDirectory()) {
File[] files = srcPath.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < files.length; i++) {
compress(files[i], out, base + files[i].getName());
}
} else {
//是文件时
if ("".equals(base)) {
out.putNextEntry(new ZipEntry(base + "/"));
base = srcPath.getName();
}
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(srcPath);
byte[] data = new byte[4096];
int b;
while ((b = in.read(data)) != -1) {
out.write(data, 0, b);
}
in.close();
}
}