Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java解压zip

作者:ー辈ふ只寵你人   发布日期:2025-10-27   浏览:43

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);
    }
}

解释说明:

  1. unzip 方法:该方法接收两个参数,zipFilePath 是 ZIP 文件的路径,destDir 是解压后文件存放的目标目录。
  2. 创建目标目录:如果目标目录不存在,则创建它。
  3. 读取 ZIP 文件:使用 ZipInputStream 读取 ZIP 文件,并逐个处理其中的每个条目(文件或文件夹)。
  4. 处理文件和文件夹:对于每个条目,如果是文件夹则创建文件夹;如果是文件,则创建相应的文件并写入内容。
  5. 安全检查newFile 方法确保解压后的文件不会超出目标目录范围,防止路径遍历攻击。
  6. 主方法:提供了一个简单的示例,指定了 ZIP 文件路径和目标目录。

希望这段代码能帮助你完成解压任务。

上一篇:java 基本数据类型

下一篇:java根据list中的对象某个属性排序

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站