随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
在前面的文章中都是将单个文件或者文件夹进行压缩,现在我们可以把不同路劲下的多个文件或者文件夹压缩到一起,生成指定的压缩文件,这里使用的是java自带的压缩方式,不支持中文无乱码:
测试类Test:
package com.home;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
try {
ZipUtil.ZipFiles(new File("D:\\test\\test.zip"), new File(
"D:\\test\\test.pdf"), new File("D:\\test\\test1"),
new File("D:\\test\\test2"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
ZipUtil:
package com.home;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
/**
* 压缩接口
*
* @param zip
* @param srcFiles
* @throws IOException
*/
public static void ZipFiles(File zip, File... srcFiles) throws IOException {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipFiles(zos, "", srcFiles);
} finally {
if (zos != null) {
zos.close();
}
}
}
/**
* 压缩文件
*
* @param out
* @param path
* @param srcFiles
*/
private static void ZipFiles(ZipOutputStream out, String path,
File... srcFiles) {
path = path.replaceAll("\\*", "/");
if (!path.endsWith("/")) {
path += "/";
}
byte[] buf = new byte[1024];
try {
for (int i = 0; i < srcFiles.length; i++) {
if (srcFiles[i].isDirectory()) {
File[] files = srcFiles[i].listFiles();
String srcPath = srcFiles[i].getName();
srcPath = srcPath.replaceAll("\\*", "/");
if (!srcPath.endsWith("/")) {
srcPath += "/";
}
out.putNextEntry(new ZipEntry(path + srcPath));
ZipFiles(out, path + srcPath, files);
} else {
FileInputStream in = new FileInputStream(srcFiles[i]);
out.putNextEntry(new ZipEntry(path + srcFiles[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}