java 解压缩文件
时间: 2024-06-11 17:03:34 浏览: 112
在Java中,解压缩文件通常使用`java.util.zip`包提供的类,如`ZipInputStream`, `ZipFile`, 或者第三方库如Apache Commons Compress或Java Advanced Imaging (JAI)。以下是使用这些工具的基本步骤:
1. 使用`ZipInputStream`或`ZipFile`解压`.zip`文件:
```java
import java.io.*;
import java.util.zip.*;
public void unzipFile(String zipPath, String destDir) {
try {
ZipFile zip = new ZipFile(zipPath);
Enumeration<ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String filePath = destDir + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractEntry(zip, entry, new File(filePath));
}
}
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void extractEntry(ZipFile zip, ZipEntry entry, File destination) throws IOException {
InputStream in = zip.getInputStream(entry);
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.close();
}
```
2. 使用第三方库(如Apache Commons Compress):
如果你选择使用Apache Commons Compress,首先需要添加依赖。例如,你可以通过Maven添加`commons-compress`依赖:
```xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
```
代码示例:
```java
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFileFactory;
public void unzipWithApacheCommons(String zipPath, String destDir) {
try (ZipFile zip = ZipFileFactory.create(new File(zipPath))) {
for (ZipArchiveEntry entry : zip) {
if (!entry.isDirectory()) {
String filePath = destDir + File.separator + entry.getName();
Files.copy(zip.getInputStream(entry), Paths.get(filePath));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
使用以上方法时,请确保正确处理可能出现的异常,并确保有足够的权限访问和写入目标目录。
阅读全文