import java.io.*;
import java.util.zip.*;
public class UnzipFile {
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 {
// fix for Windows-created archives
File parent = newFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
// write file content
try (FileOutputStream fos = new FileOutputStream(newFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
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/directory";
unzip(zipFilePath, destDir);
}
}
unzip 方法:该方法接收两个参数,一个是压缩文件的路径 (zipFilePath),另一个是解压后的目标目录 (destDir)。它首先检查目标目录是否存在,如果不存在则创建该目录。
ZipInputStream:用于读取 ZIP 文件的内容。通过 getNextEntry() 方法逐个读取 ZIP 文件中的条目(文件或目录)。
处理目录和文件:对于每个条目,如果是目录,则创建相应的目录;如果是文件,则创建父级目录(如果不存在),然后将文件内容写入到目标位置。
newFile 方法:确保解压出来的文件不会超出指定的目标目录范围,防止路径遍历攻击。
main 方法:提供了一个简单的入口点,你可以根据需要修改 zipFilePath 和 destDir 的值来测试解压功能。
zipFilePath 和 destDir 为实际的文件路径。下一篇:java word转html
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站