Java – 创建受密码保护的 Zip 文件

Java – 创建受密码保护的 Zip 文件

原文: https://howtodoinjava.com/java/io/how-to-create-password-protected-zip-files-in-java/

本教程介绍使用非常有用的库 Zip4j 创建受密码保护的 zip 文件。 Java 默认情况下不提供文件密码保护的任何支持。 尽管它对创建/提取 zip 文件具有很好的 API 支持。 还有一些其他有用的库,它们同样好,有时甚至比 zip4j 更好,但是它们也使用一些本机代码,这使得它们的使用平台在某种程度上依赖于。 Zip4j 完全使用 Java 代码,没有任何本机代码的支持,因此它更适合我。

Zip4j 提供以下特性:

  • 创建,添加,提取,更新,从 Zip 文件中删除文件
  • 读/写受密码保护的 Zip 文件
  • 支持 AES 128/256 加密
  • 支持标准 Zip 加密
  • 支持 Zip64 格式
  • 支持存储(无压缩)和压缩压缩方法
  • 从分卷 Zip 文件创建或提取文件(例如:z01,z02,…zip)
  • 支持 Unicode 文件名
  • 进度监视器

1)下载 Zip4j 库并将其包含到项目中

要下载 Zip4j 库,请转到其 zip4j 下载页面并下载其最新版本(直到今天的zip4j_1.3.2.jar)。

zip4j.jar文件添加到您项目的类路径中。

2)创建受密码保护的 zip 文件的示例

现在,您可以使用以下代码创建受密码保护的存档。

您将需要使用 Java 6 来运行示例。

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();
		}
	}
}

还有其他有用的用例,您也可以查看其源码发行版zip4j_examples_eclipse_1.3.2.zip。 签出这个非常有用的库。

祝您学习愉快!

参考: http://www.lingala.net/zip4j/