批量压缩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);
                    }
                }
            }
        }
    }
}


相关文章
|
开发者
MacM1安装MAT全流程安装指南
MAT作为开发者分析堆栈快照信息的常用工具,本文介绍了在MBP M1中安装指南。
3271 1
MacM1安装MAT全流程安装指南
|
Ubuntu Linux
linux实用技巧:ubuntu16.04安装BeyondCompare文件/文件夹对比工具
linux实用技巧:ubuntu16.04安装BeyondCompare文件/文件夹对比工具
linux实用技巧:ubuntu16.04安装BeyondCompare文件/文件夹对比工具
|
8月前
|
JSON API 数据格式
手把手教你抓取京东商品评论:API 接口解析与 Python 实战
京东商品评论蕴含用户对产品质量、体验和服务的真实反馈,分析这些数据有助于企业优化产品和满足用户需求。由于京东未提供官方API,需通过逆向工程获取评论数据。其主要接口为“商品评论列表接口”,支持按商品ID、评分、排序方式等参数获取评论,返回JSON格式数据,包含评论列表、摘要(如好评率)及热门标签等信息。
|
JavaScript Java 数据库
生鲜超市|基于SprinBoot+vue的生鲜超市系统(源码+数据库+文档)
生鲜超市|基于SprinBoot+vue的生鲜超市系统(源码+数据库+文档)
248 0
|
移动开发 前端开发
基于jeecg-boot的flowable流程审批时增加下一个审批人设置
基于jeecg-boot的flowable流程审批时增加下一个审批人设置
1352 0
|
存储 安全 网络安全
Python编程--使用PyPDF解析PDF文件中的元数据
Python编程--使用PyPDF解析PDF文件中的元数据
573 1
|
数据采集 JSON API
淘宝商品评论数据采集教程丨淘宝商品评论数据接口Taobao.item_review
`淘宝开放平台的Taobao.item_review API让开发者能获取商品评论。步骤包括注册开发者账号,创建应用获取API密钥,理解和使用请求参数,签名验证并发送HTTP请求。返回的JSON数据包含评论详情,需解析并清洗后分析。注意频率限制和用户隐私保护。此接口助力商家分析用户反馈,优化经营策略。`
|
安全 程序员 数据库
程序员必知:xadmin快速搭建后台管理系统
程序员必知:xadmin快速搭建后台管理系统
496 0
|
Java Maven
Maven标准目录结构介绍
src/main/java:源代码目录 src/main/resources:资源文件目录 src/test/java:测试代码目录 src/test/resources:测试资源文件目录 这里只是部分结构,像jar或者war工程如果有源代码的一般是这个结构,但这个结构也不是必须的,不同的项目不同的需求也可以有不同的结构。
941 0
Maven标准目录结构介绍
|
消息中间件 弹性计算 固态存储
256变4096:分库分表扩容如何实现平滑数据迁移?
本文作者就一个高德打车弹外订单系统进行了一次扩分库分表和数据库迁移。
256变4096:分库分表扩容如何实现平滑数据迁移?