首页 > 其他分享 >压缩工具-ZipUtil

压缩工具-ZipUtil

时间:2024-04-26 16:33:05浏览次数:11  
标签:zipOutputStream 压缩工具 keepDirStructure error param new import ZipUtil

介绍:提供了两个压缩方法
1、压缩指定文件夹
2、根据文件列表压缩
代码实现:

/*
 * 打工人的学习代码...
 */
package com.mybatis.tool.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * <B>Description: Zip工具</B>
 * </P>
 * Revision Trail: (Date/Author/Description)
 * 2024/4/26 Ryan Huang CREATE
 *
 * @author Ryan Huang
 * @version 1.0
 */
public class ZipUtil {

    private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    private static final int  BUFFER_SIZE = 2 * 1024;


    /**
     * 压缩文件
     * @param srcDir 源目录
     * @param outputStream 输出流
     * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败
     */
    public static void toZip(String srcDir, OutputStream outputStream, boolean keepDirStructure){
        long startTime = System.currentTimeMillis();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            File sourceFile = new File(srcDir);
            compress(sourceFile, zipOutputStream, sourceFile.getName(), keepDirStructure);
            long endTime = System.currentTimeMillis();
            logger.info("压缩完成,耗时:{}ms", endTime - startTime);
        }catch (Exception e){
            logger.error("zip error", e);
            throw new RuntimeException("zip error");
        }
    }

    /**
     * 压缩文件
     * @param srcFileList 源文件列表
     * @param outputStream 输出流
     */
    public static void toZip(List<File> srcFileList, OutputStream outputStream){
        long startTime = System.currentTimeMillis();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            for (File file : srcFileList) {
                byte[] buf = new byte[BUFFER_SIZE];
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                int len;
                try (FileInputStream fileInputStream = new FileInputStream(file)) {
                    while ((len = fileInputStream.read(buf)) != -1) {
                        zipOutputStream.write(buf, 0, len);
                    }
                }catch (IOException e){
                    logger.error("zip error", e);
                    throw new RuntimeException("zip error");
                }
                zipOutputStream.closeEntry();
            }
            long endTime = System.currentTimeMillis();
            logger.info("压缩完成,耗时:{}ms", endTime - startTime);
        }catch (Exception e){
            logger.error("zip error", e);
            throw new RuntimeException("zip error");
        }
    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zipOutputStream 压缩输出流
     * @param name 压缩后的名称
     * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zipOutputStream, String name, boolean keepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            zipOutputStream.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream inputStream = new FileInputStream(sourceFile);
            while ((len = inputStream.read(buf)) != -1){
                zipOutputStream.write(buf, 0, len);
            }
            zipOutputStream.closeEntry();
            inputStream.close();
        }else{
            File[] fileList = sourceFile.listFiles();
            if(fileList == null || fileList.length == 0){
                //需保留原来的文件结构时,需要对空文件夹进行处理
                if(keepDirStructure){
                    zipOutputStream.putNextEntry(new ZipEntry(name + "/"));
                    zipOutputStream.closeEntry();
                }
            }else{
                for(File file : fileList){
                    if(keepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zipOutputStream, name + "/" + file.getName(), keepDirStructure);
                    }else {
                        compress(file, zipOutputStream, file.getName(), keepDirStructure);
                    }
                }
            }
        }
    }
}

标签:zipOutputStream,压缩工具,keepDirStructure,error,param,new,import,ZipUtil
From: https://www.cnblogs.com/IamHzc/p/18160380

相关文章

  • 基于jackson的json key压缩工具类
    packagecom.zipkey;importcom.fasterxml.jackson.annotation.JsonInclude;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.MapperFeature;importcom.fasterxml.......
  • 基于清晰度优先的安卓图片压缩工具的二次开发小记。
    原程序:https://github.com/lexluthors/CompressTools-Android工具特性:这是和微信压缩效果类似的压缩方式,采用底层压缩。尽量无损压缩图片,保持清晰度最优。可以对比原生方法bitmap.compress(CompressFormat.JPEG,quality,fileOutputStream);占用内存少,支持压缩生成原图分......
  • 如何用压缩工具对指定文件进行备份保存
    使用场景:当你的程序文件需要每日自动备份时 脚本文件:新建记事本文件,重命名为bak.bat@echooff::设置7z的命令行程序路径setzip7=D:\\7-Zip\\7z.exe::设置压缩包保存路径setSave=E:\\datebak::当天日期,备份文件名setcurdate=%date:~0,4%-%date:~5,2%-%date:~8,2%::......
  • makecab命令工具 无损数据压缩工具
    CabinetMaker-无损数据压缩工具MAKECAB[/V[n]][/D变量=值...][/L目录]源文件[目标文件]MAKECAB[/V[n]][/D变量=值...]/F指令文件[...]源文件要压缩的文件。目标文件压缩后的文件名。如果省略,将用下划线(_)替换源文件名的最后一个字符作为目标文件名。......
  • UPX 可执行文件压缩工具的介绍与使用
    UPX是什么UPX全称是"UltimatePackerforeXecutables",是一个免费、开源、编写、可扩展、高性能的可执行程序打包程序。换句话说一个可执行文件的压缩工具。主要的功能是将可执行的二进制程序、动态链接库和其他的二进制文件压缩为更小的体积,UPX通常可以将文件大小减少50%......
  • JS压缩谁最强?对比5款JS代码压缩工具
    JS压缩谁最强?对比5款JS代码压缩工具JS压缩,似乎是很简单的一个事情,通常在线就可以完成。但不同网站或工具提供的JS压缩,效果差异不小。本文,测试国内外5个JS在线压缩工具,看看谁的效果最好。测试用JS代码(注:这段代码来下面要测试的JShaman网站,以压缩这段代码为例,看不同的工具压缩后......
  • Javascript压缩工具
    javascriptcompressor.com(在线压缩)shrinksafe.dojotoolkit.org(在线文件压缩)dean.edwards.name/packer(在线压缩)YUICompressor(使用命令行来压缩,需要JAVA虚拟机来运行压缩程序 有个压缩比更高的,是个要注册的软件...javascriptObfuscatorhttp://www.javascript-source.......
  • RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2 新增解压缩工具类ZipHelper
    在项目对文件进行解压缩是非常常用的功能,对文件进行压缩存储或传输可以节省流量与空间。压缩文件的格式与方法都比较多,比较常用的国际标准是zip格式。压缩与解压缩的方法也很多,在.NET2.0开始,在System.IO.Compression中微软已经给我们提供了解压缩的方法GZipStream。对于GZipSt......
  • GZIPUtils工具类
    GZIPUtils.java工具类importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.zip.GZIPInputStream;importjava.util.zip.GZIPOutputStream;importorg.apache.commons.codec.binary.StringUtils;pub......
  • 打包exe文件,使用工具 rar老牌压缩工具,你没看错
    废话不多说,看完点个赞整理好所有的问题,放入一个文件夹右键文件夹,添加到压缩文件如图勾选,创建自解压格式压缩文件找到上面标签高级,点击,然后再点自解压选项选择高级,添加快捷方式看一下刚刚准备好的文件夹wbc666中的文件请对应你的文件夹名字和快捷方式的源文件,我这里......