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 文件后綴(非空時(shí)只處理固定后綴的文件)
* @return 處理結(jié)果
* @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);
//轉(zhuǎn)化文件流為壓縮文件流
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);
}
// 關(guān)閉流
byteStream.close();
//讀取的文件轉(zhuǎn)為所需的流添加到集合中
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteStream.toByteArray());
list.add(byteArrayInputStream);
}
return list;
}
/**
* 解讀zip文件
*
* @param filePath 壓縮文件路徑
* @param suffixType 文件后綴(非空時(shí)只處理固定后綴的文件)
* @return 處理結(jié)果
* @throws IOException
*/
public static List<InputStream> readZipToInputStreamList(String filePath, String suffixType) throws IOException {
File zipFile = new File(filePath);
return readZipToInputStreamList(zipFile, suffixType);
}
}
解讀zip文件,把zip文件內(nèi)的眾文件轉(zhuǎn)化成流集合,方便其他后續(xù)操作文章來源地址http://www.zghlxwxcb.cn/news/detail-690639.html
文章來源:http://www.zghlxwxcb.cn/news/detail-690639.html
到了這里,關(guān)于java 解讀zip文件,獲取壓縮包內(nèi)各文件的流的集合的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!