Java通过java.util.zip包实现ZIP文件的压缩与解压,使用ZipOutputStream压缩文件、ZipInputStream解压文件,需注意路径安全、编码问题及资源管理。

Java提供了内置的工具来处理ZIP文件的压缩与解压,主要通过java.util.zip包中的类实现,如ZipInputStream、ZipOutputStream、ZipEntry等。下面详细介绍如何在Java中进行ZIP文件的压缩和解压操作。
压缩文件为ZIP
要将一个或多个文件压缩成ZIP格式,使用ZipOutputStream配合FileOutputStream写入数据。每个被压缩的文件都需要创建一个ZipEntry对象。
示例:将多个文件打包成zip
import java.io.*;
import java.util.zip.*;
public class ZipCompressor {
public static void compressFiles(String[] fileNames, String zipFileName) throws IOException {
try (FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos)) {
byte[] buffer = new byte[1024];
for (String fileName : fileNames) {
File file = new File(fileName);
try (FileInputStream fis = new FileInputStream(file)) {
zos.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
}
}
}
}
// 使用示例
public static void main(String[] args) {
String[] files = {"file1.txt", "file2.txt"};
try {
compressFiles(files, "output.zip");
System.out.println("压缩完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
解压ZIP文件
解压ZIP文件使用ZipInputStream逐个读取ZipEntry,然后将内容写入对应的目标文件。
立即学习“Java免费学习笔记(深入)”;
示例:解压ZIP到指定目录
import java.io.*;
import java.util.zip.*;
public class ZipDecompressor {
public static void decompressZip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdirs();
}
try (FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry entry;
byte[] buffer = new byte[1024];
while ((entry = zis.getNextEntry()) != null) {
File file = new File(destDir, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
// 确保父目录存在
file.getParentFile().mkdirs();
try (FileOutputStream fos = new FileOutputStream(file)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zis.closeEntry();
}
}
}
// 使用示例
public static void main(String[] args) {
try {
decompressZip("output.zip", "extracted/");
System.out.println("解压完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项与优化建议
在实际使用中需要注意以下几点:
-
路径安全:解压时应校验
ZipEntry的名称,防止路径穿越攻击(如包含../) -
编码问题:某些ZIP文件可能使用非UTF-8编码命名文件,可考虑使用
ZipInputStream(ZipInputStream, Charset)指定编码 - 大文件处理:使用缓冲流(如上面的1KB缓冲)提升I/O性能
- 资源管理:推荐使用try-with-resources确保流正确关闭
基本上就这些。Java原生支持足够应对大多数ZIP压缩与解压需求,无需引入额外依赖。只要注意文件路径和异常处理,就能稳定运行。不复杂但容易忽略细节。










