java 解压zip
时间: 2023-11-11 14:06:25 浏览: 92
可以使用Java自带的ZipInputStream类来解压zip文件。具体步骤如下:
1. 创建ZipInputStream对象,传入要解压的zip文件的InputStream。
2. 使用getNextEntry()方法获取zip文件中的每一个entry。
3. 判断entry是否为目录,如果是则创建目录。
4. 如果不是目录,则创建输出流,将entry内容写入输出流中。
5. 关闭输出流和ZipInputStream对象。
以下是示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipExample {
public static void main(String[] args) throws IOException {
String zipFilePath = "path/to/zip/file.zip";
String destDirPath = "path/to/destination/directory";
File destDir = new File(destDirPath);
if (!destDir.exists()) {
destDir.mkdir();
}
try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirPath + 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);
}
}
}
}
```
阅读全文
相关推荐
















