import java.io.*;
import java.util.zip.*;
public class ZipUtil {
/**
* 解压指定的zip文件到目标目录
* @param zipFilePath 要解压的zip文件路径
* @param destDir 解压后文件存放的目标目录
*/
public static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// 如果目标目录不存在,则创建
if (!dir.exists()) dir.mkdirs();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
File newFile = newFile(dir, zipEntry);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
// 创建父级目录(如果需要)
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();
}
// 关闭当前的zip条目并为下一个条目做好准备
zis.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理文件名中的特殊字符,防止路径穿越等问题
* @param destinationDir 目标目录
* @param zipEntry 压缩包中的条目
* @return 安全的文件对象
* @throws IOException 如果文件名无效或存在其他IO异常
*/
private 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/folder";
unzip(zipFilePath, destDir);
}
}
unzip 方法:这是主要的解压逻辑。它接受两个参数:zipFilePath(要解压的zip文件路径)和 destDir(解压后文件存放的目标目录)。它会读取zip文件中的每个条目,并根据条目的类型(文件或目录)进行相应的处理。
newFile 方法:用于确保生成的文件路径是安全的,防止路径穿越攻击。它会检查生成的文件路径是否在目标目录内。
main 方法:提供了一个简单的测试入口,你可以修改 zipFilePath 和 destDir 来测试解压功能。
zipFilePath 和 destDir 的路径是正确的。上一篇:java assert断言
下一篇:java链式编程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站