批量导出pdf为zip文件(可以修改zip中pdf名称)

核心代码

java 复制代码
  public static void compressZip1(HashMap<String,File> map, String rootPath, String zipFileName) throws FileNotFoundException {
        FileOutputStream fileOutputStream = new FileOutputStream(zipFileName);
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(rootPath));

        try {
            for (Map.Entry<String, File> entry : map.entrySet()) {
                String fileName = entry.getKey(); // 获取文件名
                File file = entry.getValue(); // 获取文件

                FileInputStream fileInputStream = new FileInputStream(file);
                zip1(fileInputStream, zipOutputStream, fileName, file);
                fileInputStream.close();
            }

            zipOutputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            log.error("context", e);
        }finally {
            try {
                zipOutputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                log.error("context", e);
            }
        }
    }

    private static void zip1(FileInputStream fileInputStream,ZipOutputStream zipOutputStream,  String fileName, File file) throws IOException {
        // 设置自定义pdf文件名
        String newFileName = fileName + file.getName();
        ZipEntry zipEntry = new ZipEntry(newFileName);
        zipOutputStream.putNextEntry(zipEntry);

        byte[] buffer = new byte[1024*5];
        BufferedInputStream bufferStream  = new BufferedInputStream(fileInputStream);
        int length;
        // 输入缓冲流
            int read = 0;
//        while ((length = fileInputStream.read(buffer)) > 0) {
        while ((read = bufferStream.read(buffer)) != -1) {
            zipOutputStream.write(buffer, 0, read);
        }

        zipOutputStream.closeEntry();
        bufferStream.close();
    }

注意!!!

这里需要使用BufferedInputStream, 如果用的是FileInputStream 就算flush 有时候还是会文件损坏,我没再深点测试这个为啥得BufferedInputStream

相关推荐
wjhx1 分钟前
QT中对蓝牙权限的申请,整理一下
java·数据库·qt
YCY^v^5 分钟前
JeecgBoot 项目运行指南
java·学习
云小逸12 分钟前
【nmap源码解析】Nmap OS识别核心模块深度解析:osscan2.cc源码剖析(1)
开发语言·网络·学习·nmap
冰暮流星12 分钟前
javascript之二重循环练习
开发语言·javascript·数据库
风指引着方向13 分钟前
自定义算子开发入门:基于 CANN op-plugin 的扩展实践
开发语言
人间打气筒(Ada)17 分钟前
jenkins基于Pipeline发布项目
java·pipeline·jenkins·流水线·ci·cd·cicd
Fairy要carry18 分钟前
面试-GRPO强化学习
开发语言·人工智能
爬山算法22 分钟前
Hibernate(88)如何在负载测试中使用Hibernate?
java·后端·hibernate
自不量力的A同学26 分钟前
Solon AI v3.9 正式发布:全能 Skill 爆发
java·网络·人工智能
Liekkas Kono30 分钟前
RapidOCR Python 贡献指南
开发语言·python·rapidocr