Java中ZIP压缩包操作:完全指南
在现代Java开发中,经常需要打包和解包文件。ZIP是最流行的压缩格式之一,由Java标准库支持。内置的java.util.zip包提供了所有必要的工具,无需安装第三方依赖即可操作ZIP压缩包。
java.util.zip包的主要类
java.util.zip包包含几个用于操作压缩包的关键类:
- ZipOutputStream — 用于创建ZIP压缩包并向其中写入文件
- ZipInputStream — 用于读取ZIP压缩包的内容
- ZipEntry — 表示压缩包中的单个条目(文件或目录)
- ZipFile — 用于按名称直接访问压缩包中的条目
- Deflater/Inflater — 用于数据压缩/解压缩的低级类
创建ZIP压缩包
使用ZipOutputStream创建压缩包。每个添加的文件都表示为ZipEntry。以下示例将多个文件打包到一个压缩包中:
import java.io.*;import java.util.zip.*;
public class CreateZipExample { public static void main(String[] args) { // 要压缩的文件数组 String[] sourceFiles = {"file1.txt", "file2.txt", "image.png"}; String zipFileName = "archive.zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName))) { byte[] buffer = new byte[1024];
for (String filePath : sourceFiles) { File file = new File(filePath); // 在压缩包中创建条目 ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry);
// 读取文件并写入压缩包 try (FileInputStream fis = new FileInputStream(file)) { int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } zos.closeEntry(); } System.out.println("压缩包已创建: " + zipFileName); } catch (IOException e) { e.printStackTrace(); } }}解压ZIP压缩包
使用ZipInputStream读取压缩包。getNextEntry()方法依次返回压缩包中的所有条目:
import java.io.*;import java.util.zip.*;
public class ExtractZipExample { public static void main(String[] args) { String zipFileName = "archive.zip"; String outputDir = "extracted_files";
new File(outputDir).mkdir();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName))) { ZipEntry entry; byte[] buffer = new byte[1024];
while ((entry = zis.getNextEntry()) != null) { String fileName = entry.getName(); File newFile = new File(outputDir + File.separator + fileName);
// 必要时创建目录 new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) { int length; while ((length = zis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } zis.closeEntry(); System.out.println("已解压: " + fileName); } } catch (IOException e) { e.printStackTrace(); } }}