java中使用zip4j创建带密码保护的文件

在java中创建zip文件问题不大,但如果要创建带密码保护的zip文件,则可以使用
zip4j这个项目(下载地址:http://www.lingala.net/zip4j/download.php)

zip4j还支持针对普通zip文件的crud,支持AES 128/256 的加密,支持分卷zip等很多功能
下面看个例子:

import java.io.File;
import java.util.ArrayList;
 
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
 
public class CreatePasswordProtectedZipExample
{
    public static void main(String[] args)
    {
        try {
           //创建zip文件
            ZipFile zipFile = new ZipFile("C:/temp/test.zip");
             
            //增加文件到zip中
            ArrayList<File> filesToAdd = new ArrayList<File>();
            filesToAdd.add(new File("C:/temp/test1.txt"));
            filesToAdd.add(new File("C:/temp/test2.txt"));
             
            //初始化各类参数
            ZipParameters parameters = new ZipParameters();
//设置压缩模式
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
             
            //DEFLATE_LEVEL_FASTEST     - Lowest compression level but higher speed of compression
            //DEFLATE_LEVEL_FAST        - Low compression level but higher speed of compression
            //DEFLATE_LEVEL_NORMAL  - Optimal balance between compression level/speed
            //DEFLATE_LEVEL_MAXIMUM     - High compression level with a compromise of speed
            //DEFLATE_LEVEL_ULTRA       - Highest compression level but low speed
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
             
             //设置加密标志
            parameters.setEncryptFiles(true);
             
            //设置aes加密
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
             
            //AES_STRENGTH_128 - For both encryption and decryption
            //AES_STRENGTH_192 - For decryption only
            //AES_STRENGTH_256 - For both encryption and decryption

        
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
             
            //设置密码
            parameters.setPassword("123456");
             
       
            zipFile.addFiles(filesToAdd, parameters);
        }
        catch (ZipException e)
        {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java)