Java 文件压缩下载

Java多文件压缩下载

今日在做一个文件下载的需求,记录下如何使用Java制作压缩文件并下载。

在这里有个需求是说需要对内部文件名称做整理,所以我们使用Map来做循环处理

public void downloadZip(HttpServletResponse response) {
		Map<String, String> fileList = new HashMap<>();
		fileList.put("D:\\test/abc.pdf", "xxxx001.pdf");
        fileList.put("D:\\test/downtest.pdf", "yyyy001.pdf");
        if (MapUtils.isEmpty(fileList)) {
            throw new RuntimeException("No file found");
        }

        ZipOutputStream zipOutputStream = null;
        try {
            //设置响应头
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            //设置文件名称
            response.setHeader("Content-Disposition", "attachment;filename=" + "ShipmentLabels.zip");
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            for (Map.Entry<String, String> filePath : fileList.entrySet()) {
                File file = new File(filePath.getKey());
                FileInputStream fis = new FileInputStream(file);
                // 对内部文件重命名
                ZipEntry zipEntry = new ZipEntry(filePath.getValue());
                zipOutputStream.putNextEntry(zipEntry);

                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zipOutputStream.write(bytes, 0, length);
                }

                zipOutputStream.closeEntry();
                fis.close();
            }
            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if (null != zipOutputStream) {
                try {
                    zipOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值