Java Zip压缩&解压的三种方式

本文详细介绍如何使用Java的ZipFile和ZipInputStream进行文件解压,以及使用ZipOutputStream进行文件压缩的方法。文章提供了完整的代码示例,包括处理中文文件名的解决方案,并推荐了更稳定的Apache commons-compress库。
该文章已生成可运行项目,

文章内容列表

  1. 使用ZipFile解压文件
  2. 使用ZipInputStream解压文件流
  3. 使用ZipOutputStream压缩批量文件

说明:本文代码使用的是jdk自带的zip包,如果涉及中文文件名的场景可以使用apache的commons-compress包,代码相差不多,maven依赖如下:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.18</version>
        </dependency>

一、使用ZipFile解压文件

public void unzip() {
        //targetPath输出文件路径
        File targetFile = new File("targetPath");
        // 如果目录不存在,则创建
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //sourcePath压缩包文件路径
        try (ZipFile zipFile = new ZipFile(new File("sourcePath"))) {
            System.out.println("file nums:" + zipFile.size());
            Enumeration enumeration = zipFile.entries();
            while (enumeration.hasMoreElements()) {
                //依次获取压缩包内的文件实体对象
                ZipEntry entry = (ZipEntry) enumeration.nextElement();
                System.out.println("this file size:" + entry.getSize());
                String name = entry.getName();
                if (entry.isDirectory()) {
                    continue;
                }
                try (BufferedInputStream inputStream = new BufferedInputStream(zipFile.getInputStream(entry))) {
                    // 需要判断文件所在的目录是否存在,处理压缩包里面有文件夹的情况
                    String outName = "targetPath" + "/" + name;
                    File outFile = new File(outName);
                    File tempFile = new File(outName.substring(0, outName.lastIndexOf("/")));
                    if (!tempFile.exists()) {
                        tempFile.mkdirs();
                    }
                    try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile))) {
                        int len;
                        byte[] buffer = new byte[1024];
                        while ((len = inputStream.read(buffer)) > 0) {
                            outputStream.write(buffer, 0, len);
                        }
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

二、使用ZipInputStream解压文件流

public void unzipInputStream() {
        try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File("sourceFilePath")))) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zip.getNextEntry()) != null) {
                String fileName_zip = zipEntry.getName();
                System.out.println(fileName_zip);
                File file = new File("/targetPath/" + fileName_zip);
                if (fileName_zip.endsWith("/")) {
                    file.mkdir();
                } else {
                    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] byte_s = new byte[1024];
                    int num;
                    while ((num = zip.read(byte_s, 0, byte_s.length)) > 0) {
                        outputStream.write(byte_s, 0, num);
                    }
                    outputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

三、使用ZipOutputStream压缩批量文件

public void zip(Map<String, File> map) {
        //targetFilePath为导出文件路径,e.g.:/tmp/test.zip
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File("targetFilePath"))))) {
            map.forEach((fileName, file) -> {
                try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
                    //fileName必须带文件扩展名
                    ZipEntry entry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(entry);

                    int len;
                    byte[] buffer = new byte[1024];
                    while ((len = inputStream.read(buffer)) > 0) {
                        zipOutputStream.write(buffer, 0, len);
                    }
                } catch (IOException e) {
                    LOG.error("批量文件压缩IO异常", e);
                }
            });
            zipOutputStream.closeEntry();
        } catch (Exception e) {
            LOG.error("压缩excel文件失败", e);
            e.printStackTrace();
        } 
    }

 

本文章已经生成可运行项目
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值