java 解压zip文件
时间: 2023-12-03 07:38:41 浏览: 160
以下是Java解压Zip文件的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Unzip {
public static void main(String[] args) {
String zipFilePath = "example.zip"; // 压缩文件路径
String destDir = "output"; // 解压目标路径
unzip(zipFilePath, destDir);
}
private static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// 如果目标目录不存在,则创建
if (!dir.exists()) {
dir.mkdirs();
}
byte[] buffer = new byte[1024];
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File newFile = new File(destDir + File.separator + fileName);
// 如果当前ZipEntry是一个文件夹,则创建
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
// 如果当前ZipEntry是一个文件,则解压
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("解压完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文