@SneakyThrows
public static void toZip(String srcFile, String zipFilePath) {
if(StringUtils.isEmpty(zipFilePath)){
return;
}
List<String> pathList = new ArrayList<>();
pathList.add(srcFile);
toZip(pathList,zipFilePath);
}
/**
*
* @param largeFilePathList 被压缩的文件路径
* @param zipFilePath zip文件输出目录一定要存在,否则会报错
* @throws IOException
*/
@SneakyThrows
public static void toZip(List<String> largeFilePathList, String zipFilePath){
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(new File(zipFilePath)))) {
// 设置为使用ZIP64格式,支持大文件
zipOut.setUseZip64(Zip64Mode.AsNeeded);
for(String largeFilePath : largeFilePathList){
File largeFile = new File(largeFilePath);
if(!largeFile.exists()){
continue;
}
toZip(largeFile, zipOut, "");
}
}catch (Exception e){
log.error("zipFile-----出现未知异常----->",e);
throw new IOException("zipFile-----出现未知异常----->");
}
}
private static void toZip(File file, ZipArchiveOutputStream zos, String base) throws IOException {
if(file.isDirectory()) {
File[] files = file.listFiles();
if (Objects.isNull(files) || files.length <= 0) {
return ;
}
for (File child : files) {
toZip(child, zos, base + file.getName() + File.separator);
}
}else {
ZipArchiveEntry entry = new ZipArchiveEntry(base + file.getName());
entry.setSize(file.length());
zos.putArchiveEntry(entry);
byte[] buffer = new byte[1024 * 1024];
FileInputStream fis = new FileInputStream(file);
int len;
while ((len = fis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
fis.close();
zos.closeArchiveEntry();
}
}
09-16
4232

08-06
802

10-28
373
