文件打包成zip
程序员文章站
2024-03-14 15:03:46
...
文章简介
利用jdk把多个文件打包
package com.kingpoint.abc.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 将多个文件打包生成ZIP文件
* @param List<String> srcFiles 要打包文件的路径
* @param OutputStream out 打包后输出路径(包括zip文件名)
*/
public static void ZipFiles(List<String> srcFilesFullPath , OutputStream out) {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
List<File> srcFiles = new ArrayList<>();
for(String fullPath : srcFilesFullPath){
srcFiles.add(new File(fullPath));
}
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
//System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
执行以上工具类的部分代码:
String finalPath = downloadTempPath + STANDING_BOOK_ZIP_FILE + UUID.randomUUID().toString() + ".zip";
OutputStream out = new FileOutputStream(finalPath);
ZipUtil.ZipFiles(allDocFiles, out);
上一篇: vue 使用aes加密的步骤详解
下一篇: Python爬虫必备技术点(二)