参考 : https://www.cnblogs.com/zfc-java/p/8270612.html
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Auther: liyue
* @Date: 2019/7/4 11:30
* @Description:
*/
public class ZipUtil {
public static void main(String[] args) {
File[] srcFiles = {new File("/Users/leyili/Desktop/file_test/test1.jpeg"), new File("/Users/leyili/Desktop/file_test/test2.csv")};
File zipFile = new File("/Users/leyili/Desktop/file_test/111.zip");
// 调用压缩方法
zipFiles(srcFiles, zipFile,true);
}
/**
* 根据多个file对象压缩文件
* @param srcFiles
* @param zipFile
*/
public static void zipFiles(File[] srcFiles, File zipFile,Boolean isDelete) {
// 判断压缩后的文件存在不,不存在则创建
if (!zipFile.exists()) {
try {
zipFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 创建 FileOutputStream 对象
FileOutputStream fileOutputStream = null;
// 创建 ZipOutputStream
ZipOutputStream zipOutputStream = null;
// 创建 FileInputStream 对象
FileInputStream fileInputStream = null;
try {
// 实例化 FileOutputStream 对象
fileOutputStream = new FileOutputStream(zipFile);
// 实例化 ZipOutputStream 对象
zipOutputStream = new ZipOutputStream(fileOutputStream);
// 创建 ZipEntry 对象
ZipEntry zipEntry = null;
// 遍历源文件数组
for (int i = 0; i < srcFiles.length; i++) {
// 将源文件数组中的当前文件读入 FileInputStream 流中
fileInputStream = new FileInputStream(srcFiles[i]);
// 实例化 ZipEntry 对象,源文件数组中的当前文件
zipEntry = new ZipEntry(srcFiles[i].getName());
zipOutputStream.putNextEntry(zipEntry);
// 该变量记录每次真正读的字节个数
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
if (isDelete){
for (int i = 0; i < srcFiles.length; i++) {
srcFiles[i].delete();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据文件全路径名压缩文件
* @param filePaths
* @param zipFile
*/
public static void zipFiles(List<String> filePaths, File zipFile,Boolean isDelete) {
File[] srcFiles = new File[filePaths.size()];
for (int i = 0; i < filePaths.size(); i++) {
srcFiles[i] = new File(filePaths.get(i));
}
zipFiles(srcFiles, zipFile,isDelete);
}
}
END。