文
章
目
录
章
目
录
这个Java教程涵盖了使用非常有用的库Zip4J创建密码保护的Zip文件。Java默认情况下不提供任何支持文件密码保护的功能,尽管它具有创建/提取Zip文件的良好API支持。
还有另外一些有用的库,它们同样出色,有时甚至比Zip4J更好,但它们使用一些本地代码,这使得它们的用法在一定程度上依赖于平台。Zip4J使用完全的Java代码,没有任何本地代码的支持,这就是为什么它更适合我。
1. Zip4J库
1.1 功能
Zip4J提供了以下功能:
- 创建、添加、提取、更新、删除Zip文件中的文件
- 读取/写入受密码保护的Zip文件
- 支持AES 128/256加密
- 支持标准Zip加密
- 支持Zip64格式
- 支持存储(无压缩)和Deflate压缩方法
- 创建或提取Split Zip文件中的文件(例如:z01,z02,…zip)
- 支持Unicode文件名
- 进度监视器
1.2 依赖关系
下载项目中的zip4j的最新Maven依赖关系。
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.10.0</version>
</dependency>
2. 创建密码保护的Zip文件
下面的示例是一个非常简单的例子,使用该库创建一个密码保护的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 {
//This is name and path of zip file to be created
ZipFile zipFile = new ZipFile("C:/temp/test.zip");
//Add files to be archived into zip file
ArrayList<File> filesToAdd = new ArrayList<File>();
filesToAdd.add(new File("C:/temp/test1.txt"));
filesToAdd.add(new File("C:/temp/test2.txt"));
//Initiate Zip Parameters which define various properties
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
//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);
//Set the encryption flag to true
parameters.setEncryptFiles(true);
//Set the encryption method to AES Zip Encryption
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
//Key strength 192 cannot be used for encryption. But if a zip file already has a
//file encrypted with key strength of 192, then Zip4j can decrypt this file
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
//Set password
parameters.setPassword("howtodoinjava");
//Now add files to the zip file
zipFile.addFiles(filesToAdd, parameters);
}
catch (ZipException e)
{
e.printStackTrace();
}
}
}