import java.io.*;
import java.util.zip.*;
public class Unzip {
public static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(dir, zipEntry);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
// create all non-existent folders
// else you will hit FileNotFoundException for missing dirs
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
public static void main(String[] args) {
String zipFilePath = "path/to/your/zipfile.zip";
String destDir = "path/to/destination/directory";
unzip(zipFilePath, destDir);
}
}
zipFilePath 是 ZIP 文件的路径,destDir 是解压后文件存放的目标目录。ZipInputStream 读取 ZIP 文件,并逐个处理其中的每个条目(文件或文件夹)。newFile 方法确保解压后的文件不会超出目标目录范围,防止路径遍历攻击。希望这段代码能帮助你完成解压任务。
上一篇:java 基本数据类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站