java下载文件压缩包,将文件打包成zip下载,下载文件处理文件重名,取消上传时的唯一标识

1.工具类

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 张小张
 * @describe 压缩多个文件
 * @date 2023/07/18 18:10
 */
public class ZipUtils {
    public static void downloadAndZipFiles(HttpServletResponse response, List<String> filePaths, String zipFileName) {
        try {
            // 设置响应头,告诉浏览器这是一个压缩文件,用于下载
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);

            // 创建ZipOutputStream对象
            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
            Map<String, Integer> existingFileNames = new HashMap<>();

            // 将文件逐个添加到压缩包中
            for (String filePath : filePaths) {
                File file = new File(filePath);
                if (file.exists()) {
                    addToZip(zipOut, file, existingFileNames);
                }
            }

            // 关闭ZipOutputStream
            zipOut.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addToZip(ZipOutputStream zipOut, File file, Map<String, Integer> existingFileNames) throws IOException {
        if (file.isFile()) {
            FileInputStream fis = new FileInputStream(file);

            // 获取文件名,并对文件名进行处理
            String fileName = file.getName();
            fileName = removeContentBetweenUnderscoreAndDot(fileName);

            // 处理重名文件
            if (existingFileNames.containsKey(fileName)) {
                int count = existingFileNames.get(fileName);
                count++;
                fileName = addCountToFileName(fileName, count);
                existingFileNames.put(fileName, count);
            } else {
                existingFileNames.put(fileName, 1);
            }

            // 添加到压缩包
            zipOut.putNextEntry(new ZipEntry(fileName));

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

    private static String removeContentBetweenUnderscoreAndDot(String fileName) {
        // 查找第一个'_'的位置
        int underscoreIndex = fileName.indexOf('_');

        // 查找第一个'.'的位置
        int dotIndex = fileName.indexOf('.');

        // 如果找到了'_'和'.',并且'_'在'.'之前,执行去除操作
        if (underscoreIndex != -1 && dotIndex != -1 && underscoreIndex < dotIndex) {
            // 获取'_'和'.'之间的内容
            String contentToRemove = fileName.substring(underscoreIndex, dotIndex);

            // 替换掉'_'和'.'之间的内容为空字符串
            fileName = fileName.replace(contentToRemove, "");
        }

        return fileName;
    }

    private static String addCountToFileName(String fileName, int count) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex != -1) {
            String name = fileName.substring(0, dotIndex);
            String extension = fileName.substring(dotIndex);
            return name + "(" + count + ")" + extension;
        } else {
            return fileName + "(" + count + ")";
        }
    }
}

2.调用

 //filePaths:文件url。  zipFileName:下载的压缩包名字
 List<String> filePaths = new ArrayList<String>();
 filePaths.add("opt/home/file1.xls");
 filePaths.add("opt/home/file2.xls");
 String zipFileName = "压缩包名字" + searchParam.getType() + ".zip";
 ZipUtils.downloadAndZipFiles(response, filePaths, zipFileName);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值