Java 截压缩包(zip包)-工具类

Java 截压缩包(zip包)-工具类

技术:在Java中,使用Java自带的java.util.zip.ZipFile包

代码示例如下:
注1:在下面的代码中,zipFilePath替换为要解压缩的.zip文件的实际路径,destDirectory替换为要解压到的目标目录的实际路径;接着运行unzip方法即可将.zip文件解压缩到目标目录。
注2:解压操作可能涉及到大量的文件和数据,建议在处理大型zip文件时使用适当的缓冲区大小,下面代码中使用了每次读取1024字节的缓冲区,可根据具体需要调整。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * <p>ClassName: UnzipUtil</p>
 * <p>Description: zip包解压缩工具类</p>
 * <p>Author: spring</p>
 * <p>Date: 2024-06-12</p>
 */
public class UnzipUtil {

    public static void main(String[] args) {
            String zipFilePath = "/home/kone/test20240612.zip";
            String destDirectory = "/home/kone/extracted";
            unzip(zipFilePath, destDirectory);
    }

    public static void unzip(String zipFilePath, String destDirectory) {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry = zipIn.getNextEntry();
            while (entry != null) {
                String filePath = destDirectory + File.separator + entry.getName();
                if (!entry.isDirectory()) {
                    extractFile(zipIn, filePath);
                } else {
                    File dir = new File(filePath);
                    dir.mkdir();
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
                System.out.println("Successfully extracted zip file.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)){
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = zipIn.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }

}

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值