java笔记_10_文件压缩Zip并加密(Zip4j)

1、添加依赖

Maven仓库地址:https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j

        <!--压缩-->
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.1</version>
        </dependency>

2、具体代码

package com.lyt.demo.util;

import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.File;

/**
 * @author LuLuYaa
 * @create 2023-05-10 14:15
 */
public final class ZipUtil {
    /**
     * 文件压缩并加密
     * @param filePath 文件夹路径
     * @param zipPath 压缩后的路径
     * @param password 密码
     */
    public static ZipFile zipEncrypt(String filePath, String zipPath, String password) throws ZipException {
        File file = new File(filePath);
        ZipFile zipFile = new ZipFile(zipPath);
        // 设置zip包的一些参数集合
        ZipParameters parameters = new ZipParameters();
        // 是否设置密码(此处设置为:是)
        parameters.setEncryptFiles(true);
        // 设置压缩方法
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        // 设置压缩级别
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        // 设置加密方法(Zip标准加密)
        parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
        // 压缩包密码
        parameters.setPassword(password);
        if (file.isDirectory()) {
            //文件夹
            zipFile.createZipFileFromFolder(file, parameters, false, -1L);
        } else {
            //单文件
            zipFile.createZipFile(file, parameters);
        }
        return zipFile;
    }
}

3、方法调用

  public void toZip(){
        try {
            ZipUtil.zipEncrypt("E:\\Desktop\\测试文件.xls","E:\\Desktop\\测试文件.zip","123456.");
        } catch (ZipException e) {
            e.printStackTrace();
        }
    }

 

posted @ 2023-05-10 17:26  LuLuYaa  阅读(1120)  评论(0编辑  收藏  举报