批量导出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

相关推荐
yuzhiboyouye18 分钟前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴1 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu1 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
秋饼2 小时前
Spring AI 2.0 渐进式工具披露实战:ToolSearchToolCallingAdvisor 源码机制、四种 ToolIndex 选型与多租户踩坑
java·ai·技术分享·后端开发
时间的情敌3 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu121383 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
头发还在的女程序员4 小时前
家政小程序系统源码IM已读记录:多端阅读状态怎样保持单调推进
java·spring boot·源码·家政·消息同步
敲上瘾4 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
船神丿男人5 小时前
C++ STL 入门:用 std::string 读配置,四个容易漏掉的边界
开发语言·c++
Rain的Java大神之路5 小时前
别再背参数了:Kafka、RocketMQ、RabbitMQ 的设计取舍与生产级避坑指南
java·后端·rocketmq