最近开发的时候遇到要获取到zip压缩包里面的文件内容,一开始的想法是先通过代码执行解压,然后读取文件内容,但是感觉好麻烦,于是度了一下,发现可以无需解压直接读取,而且还是JDK提供给我们的工具。
解决方案就是通过ZipInputStream来读取。
ZipInputStream在JDK中的util包中,而我们平时用的FileInputStream等都是在io包中的。
示例如下:
@Test
public void test() throws Exception {
//获取文件输入流
FileInputStream input = new FileInputStream("D:\\2022-03-28.zip");
//获取ZIP输入流(一定要指定字符集Charset.forName("GBK")否则会报java.lang.IllegalArgumentException: MALFORMED)
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(input), Charset.forName("GBK"));
//定义ZipEntry置为null,避免由于重复调用zipInputStream.getNextEntry造成的不必要的问题
ZipEntry ze;
List<List<Object>> list;
//循环遍历
while ((ze = zipInputStream.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!ze.isDirectory() && ze.toString().endsWith("xls")) {
//读取
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
InputStream stream = new ByteArrayInputStream(baos.toByteArray()); //excel 流
//根据excel输入流读取EXCEL中的数据
ExcelReader excelReader = ExcelUtil.getReader(stream);
list = excelReader.read(2, excelReader.getRowCount());
for(List<Object> objList : list){
objList.get(0);
objList.get(1);
//获取到数据进行相关处理
......
}
}
}
//一定记得关闭流
zipInputStream.closeEntry();
input.close();
}