批量压缩16万个文件夹为压缩包(.zip格式)

简介: 🍅程序员小王的博客:程序员小王的博客🍅 欢迎点赞 👍 收藏 ⭐留言 📝🍅 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕🍅java自学的学习路线:java自学的学习路线

一、需求:将16万个文件夹批量压缩成.zip文件


二、代码实现步骤

1、将某个文件夹压缩为.zip文件实现package com.tjcu.util;

package com.tjcu.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * @author :王恒杰
 * @date :Created in 2022/3/25 18:13
 * @description:测试压缩文件夹
 */
public class TestCompress {
    public static void main(String[] args) throws FileNotFoundException {
        //目前文件夹的位置
        String srcDir="D:/test/K2022022600000001";
        File file =new File (srcDir);
        //解压到的位置
        String targetPath="D:/test/";
       new  File(targetPath+file+".zip");
        FileOutputStream fos1 = new FileOutputStream(new File(srcDir+".zip"));
        boolean KeepDirStructure =true;
        toZip(srcDir, fos1, KeepDirStructure);
    }
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private static final int  BUFFER_SIZE = 2 * 1024;
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }
                }
            }
        }
    }
}


2、判断是否需要保留原来的文件结构

 // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }


三、循环遍历文件夹进行压缩最终版

package com.tjcu;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class TestZip {
    public static void main(String[] args) throws IOException {
        String srcDir=null;
        FileOutputStream fos1=null;
        String targetPath="D:\\20220325\\";
        File file =new File ("F:\\亿米报备");
        File filetarget =null;
        File[] fileList = file.listFiles();
        boolean KeepDirStructure =true;
        for (File file2 : fileList) {
            srcDir=file2.getAbsolutePath();
            System.out.println(targetPath+file2.getName()+".zip");
            filetarget =new  File(targetPath+file2.getName()+".zip");
            fos1 = new FileOutputStream(filetarget);
            toZip(srcDir, fos1, KeepDirStructure);
            System.out.println(srcDir);
        }
        fos1.close();
    }
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private static final int  BUFFER_SIZE = 2 * 1024;
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }
                }
            }
        }
    }
}


相关文章
|
云安全 开发框架 人工智能
|
计算机视觉
AutoCAD *.dxf文件解析,使用dxflib搞定polyline/spline/ellipse等复杂图形(★firecat推荐★)
AutoCAD *.dxf文件解析,使用dxflib搞定polyline/spline/ellipse等复杂图形(★firecat推荐★)
3422 0
AutoCAD *.dxf文件解析,使用dxflib搞定polyline/spline/ellipse等复杂图形(★firecat推荐★)
|
10月前
|
人工智能 安全 机器人
保姆级教程:2026年本地部署OpenClaw+阿里云部署Clawdbot+集成Telegram步骤(含代码可直接复制)
在AI自动化办公与跨终端协同需求爆发的2026年,OpenClaw(原Clawdbot、Moltbot)凭借“自然语言驱动、多场景适配、零技术门槛”的核心优势,成为个人与轻量团队的首选智能AI助手,无需专业编程基础,就能轻松完成文档处理、代码生成、会议纪要整理、多模态解析等多元化办公任务,堪称“全天候在线的AI数字助理”。
1617 2
|
缓存 数据安全/隐私保护 芯片
中控网 item_search - 根据关键词获取公司列表接口对接全攻略:从入门到精通
中控网item_search接口支持通过关键词批量检索企业信息,涵盖行业、地域、资质等维度,适用于供应商挖掘、市场调研等场景。本攻略详解接口调用、签名生成、分页获取及优化策略,助力开发者高效对接,快速实现精准企业数据采集与应用。
|
6月前
|
存储 缓存 运维
从云端到产线:汽车生产线密钥注入系统的架构设计
本文剖析汽车量产中关键却易被忽视的环节——密钥注入系统(KDPS)。它并非KMS附属,而是直连产线节拍的执行系统。面对60秒节拍、多供应商ECU、物理可接触等严苛约束,需在安全、速度与兼容性间精准平衡:推荐密钥预生成+安全缓存、三重防护注入通道、可插拔适配层架构。
599 0
|
10月前
|
Unix Linux Shell
Linux tr命令详细使用教程
tr是Linux中轻量高效的字符处理命令,专注字符翻译、重复压缩与指定删除,纯内存流式处理。本文详解其语法、四大选项(-c/-d/-s/-t)、字符集写法(范围/转义/字符类等)及10+实战场景,助新手快速掌握核心用法。
|
10月前
|
人工智能 安全 开发工具
Skills 与 MCP 延迟加载:谁更高效、稳定与可控?——开发者工具架构的深度对比
本文深度对比Anthropic的Claude Skills与MCP延迟加载工具:从架构、性能、稳定性、安全性和开发体验五维度分析。Skills高效易用但控制受限;MCP灵活可控却需自主运维。二者非互斥,混合架构才是未来趋势。(239字)
1299 10
|
人工智能 开发者
通义千问三款主力模型再降价,最高降幅85%
通义千问三款主力模型再降价,最高降幅85%
11754 12
通义千问三款主力模型再降价,最高降幅85%
|
12月前
|
人工智能 数据可视化 安全
WhatsApp Business API 怎么用?阿里云 Chat App 常见问题(持续更新)
全面解答阿里云 Chat App 消息服务高频问题,涵盖 WhatsApp Business 账号注册、模板审核、API 集成、多通道发送、计费规则、AI 机器人配置、安全合规等。出海企业必备指南,助您高效触达全球 30 亿用户。
1979 0
|
SQL 分布式数据库 Apache
网易游戏 x Apache Doris:湖仓一体架构演进之路
网易游戏 Apache Doris 集群超 20 个 ,总节点数百个,已对接内部 200+ 项目,日均查询量超过 1500 万,总存储数据量 PB 级别。
1530 3
网易游戏 x Apache Doris:湖仓一体架构演进之路