当前位置: 首页 > article >正文

压缩为zip和gzip工具类

一、压缩为zip工具类

package com.chinamobile.interfaces.biz.utils;

import com.chinamobile.interfaces.biz.config.SignConfig;
import com.chinamobile.interfaces.biz.constant.Constants;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.AesKeyStrength;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Zip工具类
 *
 * @author: lp
 */
public class ZipUtil {

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

    /**
     * 生成zip文件
     * 1.csv文件->压缩成zip
     * 2.产生DataSign.txt文件
     * 3.将1和2两个文件,压缩成zip,密码在yml配置
     *
     * @param list
     * @param fileName
     * @param clazz
     * @param <T>
     */
    public static <T> void generateZip(List<T> list, String fileName, Class<T> clazz) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        byte[] bytes = CsvUtil.exportToByteArray(list, clazz);
        byte[] innerZipBytes = ZipUtil.createZipFromByteArray(bytes, fileName + ".csv");
        byte[] signBytes = SignUtil.getEncryptedSignature(bytes);
        List<byte[]> fileDatas = new ArrayList<>();
        List<String> fileNames = new ArrayList<>();
        fileDatas.add(signBytes);
        fileDatas.add(innerZipBytes);
        fileNames.add(Constants.SIGN_TEXT_NAME);
        fileNames.add(fileName + ".zip");
        ZipUtil.createEncryptedZip(fileDatas, fileNames, SignConfig.getZipPath() + fileName + ".zip");
    }

    /**
     * 创建ZIP文件
     *
     * @param data      数据
     * @param entryName 条目名称
     * @return
     * @throws IOException
     */
    public static byte[] createZipFromByteArray(byte[] data, String entryName) throws IOException {
        File tempFile = new File(entryName);
        File tempZip = null;
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            fileOutputStream.write(data);
            tempZip = cn.hutool.core.util.ZipUtil.zip(tempFile);
            return cn.hutool.core.io.FileUtil.readBytes(tempZip);
        } finally {
            boolean fileFlag = tempFile.delete();
            if (!fileFlag) {
                log.error("文件删除异常{}", entryName);
            }
            if (tempZip != null) {
                boolean fileZipFlag=tempZip.delete();
                if (!fileZipFlag) {
                    log.error("压缩文件删除异常{}", entryName);
                }
            }
        }
    }

    /**
     * 创建zip文件(设置默认密码)
     *
     * @param filesData  数据集合
     * @param fileNames  文件名集合
     * @param outputPath 输出路径
     * @throws IOException
     */
    public static void createEncryptedZip(List<byte[]> filesData, List<String> fileNames, String outputPath) throws IOException {
        createEncryptedZip(filesData, fileNames, outputPath, SignConfig.getZipPwd());
    }

    /**
     * 创建zip文件并设置密码
     *
     * @param filesData  数据集合
     * @param fileNames  文件名集合
     * @param outputPath 输出路径
     * @param password   压缩密码
     * @throws IOException
     */
    public static void createEncryptedZip(List<byte[]> filesData, List<String> fileNames, String outputPath, String password) throws IOException {
        // 创建输出文件
        File outputFile = new File(outputPath);
        // 创建ZipFile对象
        ZipFile zipFile = new ZipFile(outputFile, password.toCharArray());
        // 设置ZIP参数,包括加密
        ZipParameters zipParameters = new ZipParameters();
        zipParameters.setEncryptFiles(true);
        zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
        // 添加每个文件到ZIP文件
        for (int i = 0; i < filesData.size(); i++) {
            byte[] fileData = filesData.get(i);
            String fileName = fileNames.get(i);
            // 设置ZIP参数中的文件名
            zipParameters.setFileNameInZip(fileName);
            // 创建一个ByteArrayInputStream来读取字节数组
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);
            // 添加流到ZIP文件
            zipFile.addStream(byteArrayInputStream, zipParameters);
            // 关闭流
            byteArrayInputStream.close();
        }
    }

    /**
     * 解压文件到指定的目录
     *
     * @param zipFilePath 文件所在路径
     * @param outputPath  解压的路径
     * @throws IOException
     */
    public static void extractZipFile(String zipFilePath, String outputPath) throws IOException {
        File zipFile = new File(zipFilePath);
        ZipFile zip = new ZipFile(zipFile);
        zip.extractAll(outputPath);
    }


    /**
     * 压缩多个文件,指定文件夹为.zip
     *
     * @param sourceDirPath 源文件所在文件夹路径
     * @param zipFilePath   目标压缩文件全路径,包含文件名
     * @throws IOException
     */
    public static void compressFiles(String sourceDirPath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            File dir = new File(sourceDirPath);
            compress(dir, dir, zos);
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    /**
     * 压缩单个指定文件为.zip
     *
     * @param sourceFilePath 源文件路径,包含文件名
     * @param sourceDirPath  源文件所在文件夹路径
     * @param zipFilePath    目标压缩文件全路径,包含文件名
     * @throws IOException
     */
    public static void compressFile(String sourceFilePath, String sourceDirPath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);
        try {
            File file = new File(sourceFilePath);
            File dir = new File(sourceDirPath);
            compress(file, dir, zos);
        } finally {
            if (zos != null) {
                zos.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    private static void compress(File sourceFile, File sourceDir, ZipOutputStream zos) throws IOException {
        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    compress(file, sourceDir, zos);
                }
            }
        } else {
            ZipEntry entry = new ZipEntry(sourceFile.getPath().substring(sourceDir.getPath().length() + 1));
            zos.putNextEntry(entry);
            try (FileInputStream fis = new FileInputStream(sourceFile)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, len);
                }
            }
            zos.closeEntry();
        }
    }

}

二、压缩为gzip工具类

package com.chinamobile.interfaces.biz.utils;

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

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipException;

/**
 * gzip工具类
 *
 * @author: cwf
 */
public class GzipUtil {
    private static final Logger log = LoggerFactory.getLogger(GzipUtil.class);

    /**
     * 使用gzip压缩文件
     *
     * @param sourceFilePath 要压缩的文件路径
     * @param targetGzipFilePath 压缩后的gzip文件路径
     * @throws IOException 如果发生I/O异常
     */
    public static void compressGzipFile(String sourceFilePath, String targetGzipFilePath) throws IOException {
        try(
        FileInputStream fileInputStream = new FileInputStream(sourceFilePath);
        FileOutputStream fileOutputStream = new FileOutputStream(targetGzipFilePath);
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream);
        ) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) > 0) {
                gzipOutputStream.write(buffer, 0, bytesRead);
            }
        }
//        gzipOutputStream.close();
//        fileOutputStream.close();
//        fileInputStream.close();
    }

    /**
     * 解压gzip文件
     *
     * @param inputFilePath        待解压文件的具体路径
     * @param outputDirectoryPath  目标目录路径
     * @throws IOException 如果文件读取或写入发生错误
     */
    public static void decompressGzipFile(String inputFilePath, String outputDirectoryPath) throws IOException {
        // 确保目标目录存在
        File outputDirectory = new File(outputDirectoryPath);
        if (!outputDirectory.exists()) {
           boolean flag= outputDirectory.mkdirs();
           if(!flag){
               log.error("文件夹创建异常",outputDirectoryPath);
           }
        }

        // 获取解压后的文件名
        String outputFileName = new File(inputFilePath).getName().replace(".gz", "");
        File outputFile = new File(outputDirectoryPath, outputFileName);

        try (
                FileInputStream fis = new FileInputStream(inputFilePath);
        		BufferedInputStream bis = new BufferedInputStream(fis);
                GZIPInputStream gzis = new GZIPInputStream(bis);
                FileOutputStream fos = new FileOutputStream(outputFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos)
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        }
    }

    public static void decompressGzipFileNew(String gzFile, String resultFile){
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(gzFile));
             GZIPInputStream gis = new GZIPInputStream(bis);
             FileOutputStream fos = new FileOutputStream(resultFile)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            System.out.println("Done decompressing the file: " + resultFile);

        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Error decompressing file: " + e.getMessage());
            if (e instanceof ZipException) {
                System.err.println("This file is not in GZIP format.");
            }
        }
    }
}


http://www.kler.cn/a/449771.html

相关文章:

  • 5QI DSCP映射
  • Gin-vue-admin(1):环境配置和安装
  • [Unity Shader][图形渲染] Shader数学基础11 - 复合变换详解
  • MES系统工作流的单元测试方案
  • 《LangChain大模型应用开发》书籍分享
  • 算法设计期末复习
  • MySQL快速扫描
  • ios按键精灵脚本开发:ios悬浮窗命令
  • PHP中替换某个包或某个类
  • Linux 软硬链接详解:深入理解与实践
  • Ubuntu下ESP32-IDF开发环境搭建
  • C++ 虚函数、虚函数表、静态绑定与动态绑定笔记
  • 记录--uniapp 安卓端实现录音功能,保存为amr/mp3文件
  • Blazor项目中使用EF读写 SQLite 数据库
  • 在Ubuntu上通过Docker部署NGINX服务器
  • 第三节:GLM-4v-9B数据加载之huggingface数据加载方法教程(通用大模型数据加载实列)
  • 96 vSystem
  • 区块链与比特币:技术革命的双子星
  • ImportError: DLL load failed while importing jiter
  • 工信部“人工智能+”制造行动点亮CES Asia 2025
  • 便捷的线上游戏陪玩、线下家政预约以及语音陪聊服务怎么做?系统代码解析
  • 基于Spring Boot的电影网站系统
  • K8S Ingress 服务配置步骤说明
  • 1114 Family Property (25)
  • 【环境搭建】Python、PyTorch与cuda的版本对应表
  • 在Vue2中,el-tree组件的页面节点前三角符号仅在有下级节点时显示