Java 读取ZIP压缩包中文件数据

有个项目需要从压缩包中读取数据,然后运算。
刚开始想的是解压缩然后再读取。
就又找到了个直接读取的。
主要是用到了ZipEntry。
多个压缩包嵌套也可以这样读取,思路是将压缩包里的压缩包解压出来。

import java.util.zip.*;
public static String readZip(String fileName) throws IOException{
        ZipFile zip = new ZipFile(fileName);
        File file = new File(fileName);
        String parentZipParent = file.getParent();/获取上级文件夹解压到这里
        File temp = file;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
        ZipInputStream zis = new ZipInputStream(bis);
        ZipEntry entry ;//用于获取压缩文件中的文件或文件夹
        StringBuffer sb = new StringBuffer();
        while((entry = zis.getNextEntry())!=null){
            if(entry.isDirectory()){
                //System.out.println("文件夹");
            }else{
                //System.out.println("file:"+entry.getName());
                if(entry.getName().endsWith("txt")){
                    BufferedReader reader = new BufferedReader(new InputStreamReader(zip.getInputStream(entry)));
                    String line = null;
                    while((line = reader.readLine())!=null){
                        //System.out.println(line);
                    	sb.append(line);
                    }
                } else if (entry.getName().endsWith("zip")){  //判断是否为压缩包,若是则将其解压出再读取
                	temp = new File(parentZipParent + "\\" + entry.getName());
                	//System.out.println(temp.getAbsolutePath());
                	if (!temp.getParentFile().exists()) {
                    	temp.getParentFile().mkdirs();
                	}
                   	OutputStream os = new FileOutputStream(temp);
                	通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                	InputStream is = zip.getInputStream(entry);
                	int len = 0;
                	while ((len = is.read()) !=-1) {
                	os.write(len);
                	}
                	sb.append(readZip(temp.getAbsolutePath()));
                }
            }
        }        
        return sb.toString();
    }
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值