Java 解压zip文件
时间: 2024-09-28 11:13:03 浏览: 38
在Java中,可以使用Apache Commons IO库或者内置的Java NIO(New Input/Output)包来解压ZIP文件。以下是使用这两个库的一些基本步骤:
1. **使用Apache Commons IO**:
- 首先,你需要添加Apache Commons IO到你的项目中。如果你的项目是Maven管理,可以在pom.xml里添加依赖:
```xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>
```
- 然后,使用`ZipFile`和`ZipEntry`类解压:
```java
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.zip.ZipFile;
// 创建ZipFile对象
ZipFile zip = new ZipFile("path_to_your_zip_file.zip");
try {
// 获取所有条目
Enumeration<ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
// 创建并获取输出流
File outputFile = new File(entry.getName());
FileOutputStream fos = new FileOutputStream(outputFile);
try {
// 将压缩内容写入文件
IOUtils.copy(zip.getInputStream(entry), fos);
} finally {
fos.close();
}
}
} finally {
zip.close();
}
```
2. **使用Java NIO**:
- 如果你想要更现代一些的方式,可以考虑使用`java.util.zip`包的`InflaterInputStream`配合`Files.newOutputStream`:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public void unzipZipFile(String zipFilePath, String destinationDir) throws IOException {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
Path outputFile = Paths.get(destinationDir, ze.getName());
Files.createDirectories(outputFile.getParent());
Files.copy(zis, outputFile, StandardCopyOption.REPLACE_EXISTING);
ze = zis.getNextEntry();
}
}
}
```
记得处理可能出现的异常,例如文件不存在、路径错误等,并关闭资源以释放内存和磁盘空间。
阅读全文
相关推荐













