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文件内的众文件转化成流集合,方便其他后续操作

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐