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

相关推荐
仲夏幻境6 分钟前
js利用ajax同步调用如何
开发语言·javascript·ajax
天地人-神君18 分钟前
将.idea取消git托管
java·git·intellij-idea
譕痕23 分钟前
Idea 启动报 未找到有效的 Maven 安装问题
java·maven·intellij-idea
aramae34 分钟前
详细分析平衡树--红黑树(万字长文/图文详解)
开发语言·数据结构·c++·笔记·算法
一百天成为python专家37 分钟前
python爬虫入门(小白五分钟从入门到精通)
开发语言·爬虫·python·opencv·yolo·计算机视觉·正则表达式
Mr YiRan1 小时前
多线程性能优化基础
android·java·开发语言·性能优化
CHEN5_021 小时前
【leetcode100】和为k的子数组(两种解法)
java·数据结构·算法
liyi_hz20081 小时前
O2OA (翱途)开发平台新版本发布预告:架构升级、性能跃迁、功能全面进化
android·java·javascript·开源软件
熊猫钓鱼>_>1 小时前
Java String 性能优化与内存管理:现代开发实战指南
java·开发语言·性能优化
华仔啊1 小时前
Spring事件的3种高级玩法,90%的人根本不会用
java·后端