java解压缩工具类
时间: 2023-09-03 18:14:45 浏览: 67
您好!关于Java解压缩的工具类,以下是一个示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipUtils {
public static void unzip(String zipFilePath, String destDir) throws IOException {
File dir = new File(destDir);
// 如果目标文件夹不存在,则创建
if (!dir.exists()) {
dir.mkdirs();
}
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
String filePath = destDir + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zis, filePath);
} else {
File dirPath = new File(filePath);
dirPath.mkdirs();
}
zis.closeEntry();
entry = zis.getNextEntry();
}
zis.close();
fis.close();
}
private static void extractFile(ZipInputStream zis, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
}
}
```
这个工具类中的 `unzip` 方法用于解压缩指定路径的 ZIP 文件到目标文件夹。它使用了 `ZipInputStream` 和 `ZipEntry` 类来处理 ZIP 文件的解压缩操作。您只需要调用 `unzip` 方法,传入要解压的 ZIP 文件路径和目标文件夹路径即可。
希望这个示例对您有帮助!如果有任何其他问题,请随时提问。