Java加密并压缩文件

依赖包

<dependency>
 <groupId>net.lingala.zip4j</groupId>
 <artifactId>zip4j</artifactId>
 <version>1.3.1</version>
</dependency>

 

执行用例

复制代码
package com.example.one.utils;

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;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FourZipFile {
    /**
     * 压缩单个文件并加密
     */
    public static String zipFile(String file, String fileOutPath, String passWord, String fileName) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(file);
        ZipParameters parameters = new ZipParameters();
        // 压缩方式
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        // 压缩级别
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        // 开启加密
        parameters.setSourceExternalStream(true);
        // 文件名称
        parameters.setFileNameInZip(fileName);
        if (!"".equals(passWord)) {
            parameters.setEncryptFiles(true);
            // 加密方式
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            // 设置加密密码
            parameters.setPassword(passWord.toCharArray());
        }
        try {
            ZipFile zipFile = new ZipFile(fileOutPath + fileName + ".zip");
            zipFile.addStream(fileInputStream, parameters);
            // 加密解压后删除源文件
            deleteFile(file);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return fileOutPath + fileName + ".zip";
    }

    /**
     * 删除文件
     */
    private static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    // 加密文件并压缩
    public static void main(String[] args) throws FileNotFoundException {
        String filePath =  "/Users/xuweiqiang/Desktop/test.txt";
        String fileOutPath = "/Users/xuweiqiang/Desktop/";
        String passWord = "123";
        String fileName = "hello.txt";
        String name = zipFile(filePath,fileOutPath,passWord,fileName);
        System.out.println(name);
    }

}
复制代码

 

posted @   许伟强  阅读(1288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2021-04-19 关于PHP的编码格式导致的乱码
点击右上角即可分享
微信分享提示