java将多个⽂件打包成压缩包下载java 将多个⽂件打包成压缩包下载
public void plistDownLoad(HttpServletResponse response) throws Exception {
List<String> paths = new ArrayList<>();
paths.add("C:\\Users\\ysrjs\\Desktop\\战⽹.txt");
paths.add("C:\\Users\\ysrjs\\Desktop\\宏.txt");
if (paths.size() != 0) {
String zipFilePath = "D:\\测试打包下载";
//压缩包⽂件夹
File zipFile = new File(zipFilePath);
if(!ists() && !zipFile.isDirectory()){
zipFile.mkdirs();
}
//创建压缩⽂件
File zipFile2 = new File(zipFilePath+"\\"+"下载⽂件.zip");
if(!ists()){
}
// 创建压缩输出流
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile2));
// 循环调⽤压缩⽂件⽅法将每个⽂件压缩到压缩⽂件中
for (String path : paths) {
// 该⽅法在下⾯定义All
fileAllToZip(path, zipOut);
}
// 压缩完成后,关闭压缩流
zipOut.close();
//            //拼接下载默认名称并转为ISO-8859-1格式
//            String fileName = new String(("我的压缩⽂件.zip").getBytes(),"ISO-8859-1");
//            response.setHeader("Content-Disposition", "attchment;filename="+fileName);
//
//            //该流不可以⼿动关闭,⼿动关闭下载会出问题,下载完成后会⾃动关闭
//            ServletOutputStream outputStream = OutputStream();
//            FileInputStream inputStream = new FileInputStream(zipFile2);
/
/            // 如果是SpringBoot框架,在这个路径
//            // at.util.http.fileupload.IOUtils产品
//            // 否则需要⾃主引⼊apache的 commons-io依赖
//            // copy⽅法为⽂件复制,在这⾥直接实现了下载效果
//            py(inputStream, outputStream);
//
//            // 关闭输⼊流
//            inputStream.close();
//下载完成之后,删掉这个zip包
//            File fileTempZip = new File(zipFilePath);
//            zipFile2.delete();
}
}
public static void fileAllToZip(String filePath,ZipOutputStream zipOut) throws IOException {
// 需要压缩的⽂件
File file = new File(filePath);
// 获取⽂件名称,如果有特殊命名需求,可以将参数列表拓展,传fileName
String fileName = Name();
FileInputStream fileInput = new FileInputStream(filePath);
// 缓冲
byte[] bufferArea = new byte[1024 * 10];
BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
/
/ 将当前⽂件作为⼀个zip实体写⼊压缩流,fileName代表压缩⽂件中的⽂件名称
zipOut.putNextEntry(new ZipEntry(fileName));
int length = 0;
// 最常规IO操作,不必紧张
while ((length = ad(bufferArea, 0, 1024 * 10)) != -1) {
while ((length = ad(bufferArea, 0, 1024 * 10)) != -1) {            zipOut.write(bufferArea, 0, length);
}
//关闭流
fileInput.close();
// 需要注意的是缓冲流必须要关闭流,否则输出⽆效
下载apache
bufferStream.close();
// 压缩流不必关闭,使⽤完后再关
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。