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;public class ZipFileReadUtils { public static List readZipToInputStreamList(File zipFile, String suffixType) throws IOException { List 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; } public static List readZipToInputStreamList(String filePath, String suffixType) throws IOException { File zipFile = new File(filePath); return readZipToInputStreamList(zipFile, suffixType); }}
解读zip文件,把zip文件内的众文件转化成流集合,方便其他后续操作
来源地址:https://blog.csdn.net/yssa1125001/article/details/131052635