java 实现将多个文件,压缩到同一个 zip 压缩包中
package com.yuhuofei.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Description
* @ClassName ZipUtils
* @Author yuhuofei
* @Date 2022/8/10 20:37
* @Version 1.0
*/
public class ZipUtils {
/**
* @param zipPathDir 压缩包路径 ,如 /home/data/zip-folder/
* @param zipFileName 压缩包名称 ,如 测试文件.zip
* @param fileList 要压缩的文件列表(绝对路径),如 /home/person/test/测试.doc,/home/person/haha/测试.doc
* @return
*/
public static void compressFiles(String zipPathDir, String zipFileName, List<String> fileList) {
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(zipPathDir + zipFileName)))) {
File zipFile = new File(zipPathDir);
if (!zipFile.exists()) {
zipFile.mkdirs();
}
for (String filePath : fileList) {
File file = new File(filePath);
if (file.exists()) {
int index = file.getName().lastIndexOf('.');
ZipEntry zipEntry = new ZipEntry(file.getName().substring(0, index) + "-" + dateRandom18() + file.getName().substring(index));
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[2048];
compressSingleFile(file, zos, buffer);
}
}
zos.flush();
} catch (Exception e) {
System.out.println("压缩所有文件成zip包出错" + e);
}
}
//压缩单个文件
public static void compressSingleFile(File file, ZipOutputStream zos, byte[] buffer) {
int len;
try (FileInputStream fis = new FileInputStream(file)) {
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
zos.flush();
}
zos.closeEntry();
} catch (IOException e) {
System.out.println("====压缩单个文件异常====" + e);
}
}
//生成随机数
public static String dateRandom18() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String date = simpleDateFormat.format(new Date());
String timeMillis = String.valueOf(System.currentTimeMillis());
String fiveNumber = timeMillis.substring(timeMillis.length() - 6);
String tempRandom = String.valueOf(Math.random());
String number = tempRandom.substring(tempRandom.length() - 4);
return date + fiveNumber + number;
}
//测试方法
public static void main(String[] args) {
String zipPathDir = "D:/test/";
String zipFileName = "测试文件.zip";
List<String> list = new ArrayList<>();
list.add("C:/Users/yuhuofei/Desktop/mybatis截图/00.JPG");
list.add("C:/Users/yuhuofei/Desktop/mybatis截图/01.JPG");
compressFiles(zipPathDir, zipFileName, list);
}
}
结果如下