java 文件zip打包下载 多个文件夹分类

本文介绍如何使用Java将多个文件夹分类打包成ZIP文件,关键在于利用entry.getKey()作为文件夹名,并用File.separator作为路径分隔符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

重点在于

zos.putNextEntry(new ZipEntry(entry.getKey() + File.separator + file.getName()));

这一行代码。使用entry.getKey()用来作为文件夹名,File.separator是作为分隔符(windows是  \ )

以下为项目中使用的完整代码。

public void zipMultipleFiles(Map<String, List<File>> files, HttpServletResponse response) {
        String downloadFilename = SDF.format(new Date());
        ZipOutputStream zos = null;
        InputStream in = null;
        List<String> fileNameList = new ArrayList<>();
        try {
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
            zos = new ZipOutputStream(response.getOutputStream());
            for (Map.Entry<String, List<File>> entry : files.entrySet()) {
                System.out.println(entry.getKey());
                if (EmptyUtil.isNotEmpty(entry.getValue())) {
                    for (File file : entry.getValue()) {
                        zos.putNextEntry(new ZipEntry(
                                entry.getKey() + File.separator + file.getName()));
                        in = new FileInputStream(FileUtil.getFilePath(file.getFileName()));
                        byte[] buffer = new byte[1024];
                        int r = 0;
                        while ((r = in.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        in.close();
                    }
                    zos.flush();
                }
            }
        } catch (Exception e) {
            logger.error("zipFiles error!!", e);
        } finally {
            if (EmptyUtil.isNotEmpty(zos)) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    zos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (EmptyUtil.isNotEmpty(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

参考资料:https://yq.aliyun.com/articles/700155

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值