Java 解压带密码的 ZIP 文件方法详解

在 Java 开发过程中,我们经常会遇到需要解压带密码的 ZIP 文件的情况,由于 ZIP 文件可能包含重要的数据或文件,因此保护其安全性至关重要,本文将详细介绍如何在 Java 中解压带密码的 ZIP 文件。
所需依赖
在 Java 中解压带密码的 ZIP 文件,我们需要使用 Apache Commons Compress 库,以下是添加该库到项目的步骤:
在项目的 pom.xml 文件中添加以下依赖:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
如果使用 Maven 项目,Maven 会自动下载并引入依赖。
解压带密码的 ZIP 文件
以下是一个 Java 程序示例,展示如何解压带密码的 ZIP 文件:
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ZipPasswordDecryptor {
public static void main(String[] args) {
String zipFilePath = "path/to/your/encrypted.zip";
String password = "your_password";
String outputDirectory = "path/to/output/directory";
try {
File zipFile = new File(zipFilePath);
ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(outputDirectory + "/unzip.zip"));
try (InputStream zipIn = new ZipInputStream(new FileInputStream(zipFile), StandardCharsets.UTF_8.name())) {
ZipArchiveEntry entry = (ZipArchiveEntry) zipIn.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
byte[] buffer = new byte[1024];
int len;
try (BufferedInputStream bis = new BufferedInputStream(zipIn);
BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(bis);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
while ((len = bzIn.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
byte[] fileContent = out.toByteArray();
zipOut.putArchiveEntry(new ZipArchiveEntry(entry.getName()));
zipOut.write(fileContent);
zipOut.closeArchiveEntry();
}
}
zipIn.closeEntry();
entry = (ZipArchiveEntry) zipIn.getNextEntry();
}
}
zipOut.close();
System.out.println("解压完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行程序

- 将上述代码保存为
ZipPasswordDecryptor.java文件。 - 使用
javac ZipPasswordDecryptor.java命令编译代码。 - 使用
java ZipPasswordDecryptor命令运行程序。
本文详细介绍了如何在 Java 中解压带密码的 ZIP 文件,通过使用 Apache Commons Compress 库,我们可以轻松地解压受密码保护的 ZIP 文件,在实际应用中,请确保正确处理密码和文件路径,以确保程序的安全性。