java如何解压文件
使用 java.util.zip 包解压文件
Java 提供了 java.util.zip 包来处理 ZIP 格式的压缩文件。以下是一个简单的解压示例:

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipExample {
public static void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
}
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
byte[] bytesIn = new byte[4096];
int read;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
}
}
}
使用 Apache Commons Compress 库
对于更复杂的压缩格式(如 RAR、7z 等),可以使用 Apache Commons Compress 库:

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
public class CommonsUnzip {
public static void unzip(String zipFile, String outputFolder) throws IOException {
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipFile))) {
ZipArchiveEntry entry;
while ((entry = zis.getNextZipEntry()) != null) {
File outputFile = new File(outputFolder, entry.getName());
if (entry.isDirectory()) {
outputFile.mkdirs();
} else {
outputFile.getParentFile().mkdirs();
try (OutputStream os = new FileOutputStream(outputFile)) {
IOUtils.copy(zis, os);
}
}
}
}
}
}
处理 GZIP 压缩文件
对于单个文件的 GZIP 解压缩:
import java.io.*;
import java.util.zip.GZIPInputStream;
public class GzipExample {
public static void ungzip(String gzipFile, String outputFile) throws IOException {
try (GZIPInputStream gis = new GZIPInputStream(new FileInputStream(gzipFile));
FileOutputStream fos = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = gis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
}
注意事项
解压文件时应考虑以下安全因素:
- 检查解压路径是否在目标目录内,防止路径遍历攻击
- 检查解压后文件大小,防止 ZIP 炸弹
- 处理大文件时考虑内存使用情况
- 关闭所有流资源,使用 try-with-resources 语句
这些方法提供了 Java 中处理常见压缩文件格式的基本方式,可根据具体需求进行调整和扩展。






