How to Create Password-Protected Zip Files and Unzip Them in Java – 如何在Java中创建受密码保护的Zip文件并解压缩

最后修改: 2021年 8月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In a previous tutorial, we show how to zip and unzip in Java with the help of the java.util.zip package. But we don’t have any standard Java library to create password-protected zip files.

在之前的教程中,我们展示了如何在java.util.zip包的帮助下在Java中进行压缩和解压缩。但是我们没有任何标准的Java库来创建受密码保护的压缩文件。

In this tutorial, we’ll learn how to create password-protected zip files and unzip them with the Zip4j library. It’s the most comprehensive Java library for zip files.

在本教程中,我们将学习如何使用Zip4j创建受密码保护的 zip 文件并将其解压。它是最全面的拉链文件的Java库。

2. Dependencies

2.依赖性

Let’s start by adding the zip4j dependency to our pom.xml file:

让我们先把zip4j依赖性添加到我们的pom.xml文件。

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

3. Zip a File

3.压缩一个文件

First, we’ll use the ZipFile addFile() method to zip a file named aFile.txt into a password-protected archive named compressed.zip:

首先,我们将使用ZipFile addFile()方法将一个名为aFile.txt的文件压缩到一个名为compressed.zip的受密码保护的档案中。

ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setCompressionLevel(CompressionLevel.HIGHER);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFile(new File("aFile.txt"), zipParameters);

The setCompressionLevel line is optional. We can choose from level FASTEST to ULTRA (the default is NORMAL).

setCompressionLevel行是可选的。我们可以从FASTESTULTRA级别中选择(默认为NORMAL)。

In this example, we’ve used AES encryption. If we want to use Zip standard encryption, we just replace AES with ZIP_STANDARD.

在这个例子中,我们使用了AES加密。如果我们想使用Zip标准加密,我们只需将AES替换为ZIP_STANDARD

Note that if the file “aFile.txt” doesn’t exist on disk, the method will throw an exception: “net.lingala.zip4j.exception.ZipException: File does not exist: …”

注意,如果文件 “aFile.txt “在磁盘上不存在,该方法将抛出一个异常。“net.lingala.zip4j.exception.ZipException。文件不存在:…”

To fix this, we have to make sure the file is either created manually and placed in the project folder, or we have to create it from Java:

为了解决这个问题,我们必须确保该文件是手动创建并放在项目文件夹中的,或者我们必须从Java中创建它。

File fileToAdd = new File("aFile.txt");
if (!fileToAdd.exists()) {
    fileToAdd.createNewFile();
}

Also, after we’re done with the new ZipFile, it’s a good practice to close the resource:

此外,在我们完成了新的ZipFile之后,关闭资源是一个好的做法:

zipFile.close();

4. Zip Multiple Files

4.压缩多个文件

Let’s modify the code a bit so that we can compress multiple files at once:

让我们修改一下代码,以便我们可以一次压缩多个文件。

ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);

List<File> filesToAdd = Arrays.asList(
  new File("aFile.txt"),
  new File("bFile.txt")
);

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);

Instead of using the addFile method, we use addFiles() and pass in a List of files.

我们不使用addFile方法,我们使用addFiles()并传入文件的List

5. Zip a Directory

5.压缩一个目录

We can zip a folder simply by replacing the addFile method with addFolder:

我们可以通过将addFile方法替换为addFolder来压缩一个文件夹。

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.addFolder(new File("/users/folder_to_add"), zipParameters);

6. Creating a Split Zip File

6.创建一个分割的压缩文件

We can split the zip file over several files when the size exceeds a particular limit by using createSplitZipFile and createSplitZipFileFromFolder methods:

我们可以通过使用createSplitZipFilecreateSplitZipFileFromFolder方法,在大小超过特定限制时将压缩文件分割成几个文件。

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
int splitLength = 1024 * 1024 * 10; //10MB
zipFile.createSplitZipFile(Arrays.asList(new File("aFile.txt")), zipParameters, true, splitLength);
zipFile.createSplitZipFileFromFolder(new File("/users/folder_to_add"), zipParameters, true, splitLength);

The unit of splitLength is bytes.

splitLength的单位是字节。

7. Extracting All Files

7.提取所有文件

Extracting files is just as simple. We can extract all files from our compressed.zip with the extractAll() method:

提取文件也同样简单。我们可以用extractAll()方法从我们的compressed.zip中提取所有文件。

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.extractAll("/destination_directory");

8. Extracting a Single File

8.提取单个文件

And if we just want to extract a single file from compressed.zip, we can use the extractFile() method:

而如果我们只想从compressed.zip中提取一个文件,我们可以使用extractFile()方法。

ZipFile zipFile = new ZipFile("compressed.zip", "password".toCharArray());
zipFile.extractFile("aFile.txt", "/destination_directory");

9. Conclusion

9.结语

In summary, we’ve learned how to create password-protected zip files and unzip them in Java with the Zip4j library.

综上所述,我们已经学会了如何用Zip4j库在Java中创建受密码保护的zip文件并解压

The implementation of these examples can be found over on GitHub.

这些例子的实现可以在GitHub上找到over