Java实现文件批量下载,并按照类别放到不同文件夹,并生成压缩包

实现批量下载,文件按照类别放到不同文件夹,并生成压缩包

实现思路

  1. 获取所有文件信息(类别、名称、文件路径等)
  2. 对获取的文件List进行分组,根据某个维度进行分组,可以使用 Collectors.groupingBy(XXX::getXx) 的方式分组得到Map<String, List>
  3. 创建 ZipOutputStream 对象
  4. 在ZipOutputStream 中,根据步骤2中的Map<String, List>将List中的文件通过文件流将文件输入到zip中
  5. 得到对应的zip压缩文件,再将压缩文件zip发送给前端
  6. 关闭流

代码实现

public void batchDownload(@RequestBody List<UploadInfoDto> uploadInfoListDto, HttpServletResponse response) throws Exception {
    List<UploadInfo> uploadInfos = new ArrayList<>();
    //获取对应的文件信息,存放List中
    for (UploadInfoDto dto : uploadInfoListDto) {
        List<UploadInfo> currentUploadInfos = uploadService.getUploadFile(dto);
        uploadInfos.addAll(currentUploadInfos);
    }

    String zipName = "annex.zip";
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipName, "UTF-8"));

    logger.info("开始下载");
    Map<String, List<UploadInfo>> UploadInfoGroup = uploadInfos.stream().collect(Collectors.groupingBy(UploadInfo::getClaimNo));
    // 压缩文件路径
    String zipFilePath = "billFileAnnex.zip";
    OutputStream os = response.getOutputStream();
    try {
        // 创建 ZipOutputStream 对象
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        // 循环遍历每个种类文件
        for (String category : UploadInfoGroup.keySet()) {
            // 创建一个新的 ZipEntry 对象,表示一个压缩文件
            ZipEntry entry = new ZipEntry(category + "/");//根据不同类型放入不同文件夹
            zos.putNextEntry(entry);
            for (UploadInfo uploadInfo : UploadInfoGroup.get(claimNo)) {
                Map<String, Object> metaMap = new HashMap<>();
                // 将各个种类文件夹下的文件添加到压缩文件中
                InputStream is = OSSUtil.downloadObject(uploadInfo.getFilePath());//获取oss上的文件流,下载到zip中
                addFileToZip(zos, uploadInfo, is);
            }
        }
        zos.flush();//zos必须在os之前,否则前端下载zip报错 zip: 不可预料的压缩文件末端
        zos.close();
        BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(zipFilePath)));
        byte[] buffer = new byte[1024];
        int length;
        while ((length = bis.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        bis.close();
        os.flush();
        os.close();
        logger.info("压缩完成!");
        //压缩文件发送给前端后,删除本地生成的临时文件
        File zipFile = new File(zipFilePath);
        if (zipFile.delete()) {
            logger.info("delete file success");
        }
    } catch (IOException e) {
        logger.error("批量文件下载异常");
        e.printStackTrace();
    }
}

//将文件分组存入不同文件夹
private static void addFileToZip(ZipOutputStream zos, UploadInfo uploadInfo, InputStream inputStream) throws IOException {
    // 创建一个新的 ZipEntry 对象,表示一个压缩文件中的文件
    ZipEntry entry = new ZipEntry(uploadInfo.getCategory() + "/" + uploadInfo.getFileName());
    zos.putNextEntry(entry);

    // 写入文件内容到 ZipOutputStream 中
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        zos.write(buffer, 0, length);
    }
    inputStream.close();
}

效果截图

在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,可以使用Java中的ZipOutputStream类实现文件的批量下载并合成一个压缩包。 首先,需要创建一个ZipOutputStream对象,用于将文件写入压缩包中。然后,遍历需要下载的文件列表,将每个文件逐个添加到压缩包中。 示例代码如下: ```java import java.io.*; import java.util.zip.*; public class FileDownloader { public static void main(String[] args) { // 定义要下载的文件列表 String[] filesToDownload = {"file1.txt", "file2.txt", "file3.txt"}; // 定义压缩包的文件名 String zipFileName = "download.zip"; try { // 创建压缩包输出流 FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件列表,逐个添加到压缩包中 for (String fileName : filesToDownload) { // 创建文件输入流 FileInputStream fis = new FileInputStream(fileName); // 添加压缩包条目 zos.putNextEntry(new ZipEntry(fileName)); // 将文件内容写入压缩包 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭输入流 fis.close(); // 关闭条目 zos.closeEntry(); } // 关闭压缩包输出流 zos.close(); fos.close(); System.out.println("文件下载成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们定义了要下载的文件列表,以及压缩包的文件名。然后,创建了一个ZipOutputStream对象,用于将文件写入压缩包中。在遍历文件列表的过程中,我们使用FileInputStream读取文件内容,并使用ZipOutputStream将文件内容写入压缩包中。最后,关闭压缩包输出流,完成文件下载压缩包生成

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追风少年浪子彦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值