java 解读zip文件,获取压缩包内各文件的流的集合

import cn.hutool.core.io.FileUtil;
import com.gbx.pay.service.monolith.common.exception.ui.ErrorException;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * zip文件读取工具类
 *
 * @author gbx
 */
public class ZipFileReadUtils {

    /**
     * 解读zip文件
     *
     * @param zipFile    压缩文件
     * @param suffixType 文件后缀(非空时只处理固定后缀的文件)
     * @return 处理结果
     * @throws IOException
     */
    public static List<InputStream> readZipToInputStreamList(File zipFile, String suffixType) throws IOException {
        List<InputStream> list = new ArrayList<>();
        //判断文件是否存在
        if (!zipFile.exists()) {
            throw new ErrorException("无效的zip文件");
        }
        //获取文件流
        InputStream inputStream = FileUtil.getInputStream(zipFile);
        //转化文件流为压缩文件流
        ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("gbk"));
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            //如果文件后缀条件不为空且后缀条件不符则跳过文件读取
            if (StringUtils.isNotBlank(suffixType) && !zipEntry.getName().endsWith(suffixType)) {
                continue;
            }

            //文件读取处理
            byte[] buffer = new byte[1024];
            int len;
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            while ((len = zipInputStream.read(buffer)) != -1) {
                byteStream.write(buffer, 0, len);
            }
            // 关闭流
            byteStream.close();

            //读取的文件转为所需的流添加到集合中
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteStream.toByteArray());
            list.add(byteArrayInputStream);
        }
        return list;
    }

    /**
     * 解读zip文件
     *
     * @param filePath   压缩文件路径
     * @param suffixType 文件后缀(非空时只处理固定后缀的文件)
     * @return 处理结果
     * @throws IOException
     */
    public static List<InputStream> readZipToInputStreamList(String filePath, String suffixType) throws IOException {
        File zipFile = new File(filePath);
        return readZipToInputStreamList(zipFile, suffixType);
    }
}

解读zip文件,把zip文件内的众文件转化成流集合,方便其他后续操作

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值