Java 将文件打包成 ZIP 文件
在 Java 中,你可以使用 java.util.zip 包中的类来将文件或目录打包成 ZIP 文件,以下是几种常见的方法:
使用 ZipOutputStream(基本方法)
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFileExample {
public static void main(String[] args) {
String sourceFile = "path/to/your/source/file.txt";
String zipFile = "path/to/your/output/archive.zip";
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
File fileToZip = new File(sourceFile);
zos.putNextEntry(new ZipEntry(fileToZip.getName()));
try (FileInputStream fis = new FileInputStream(fileToZip)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
System.out.println("文件已成功压缩为 ZIP");
} catch (IOException e) {
e.printStackTrace();
}
}
}
压缩整个目录
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class ZipDirectoryExample {
public static void main(String[] args) {
String sourceDir = "path/to/your/directory";
String zipFile = "path/to/your/output/archive.zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
Path sourcePath = Paths.get(sourceDir);
Files.walk(sourcePath)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourcePath.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("目录已成功压缩为 ZIP");
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 Apache Commons Compress(更高级的功能)
如果你需要更高级的压缩功能(如不同的压缩算法),可以使用 Apache Commons Compress 库:
import org.apache.commons.compress.archivers.zip.*;
import java.io.*;
import java.nio.file.*;
public class ApacheZipExample {
public static void main(String[] args) {
String sourceDir = "path/to/your/directory";
String zipFile = "path/to/your/output/archive.zip";
try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) {
Path sourcePath = Paths.get(sourceDir);
Files.walk(sourcePath)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipArchiveEntry entry = new ZipArchiveEntry(sourcePath.relativize(path).toString());
try {
zos.putArchiveEntry(entry);
Files.copy(path, zos);
zos.closeArchiveEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("目录已成功压缩为 ZIP (使用 Apache Commons Compress)");
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 路径处理:确保处理文件路径时考虑不同操作系统的路径分隔符差异
- 异常处理:妥善处理可能出现的 IOException
- 资源管理:使用 try-with-resources 语句确保流正确关闭
- 中文文件名:如果处理中文文件名,可能需要设置编码:
ZipEntry zipEntry = new ZipEntry(entryName.getBytes("UTF-8"), entryName); - 大文件处理:对于大文件,考虑使用缓冲区提高性能
方法可以根据你的具体需求选择使用,方法一适合单个文件,方法二适合整个目录,方法三提供了更高级的功能。
