java 关于压缩包文件的解压

 

/** 
     * 解压zip文件 
     *  
     * @param sourceFile 解压文件存放路径
     *            ,待解压的zip文件; toFolder,解压后的存放路径 
     * @throws Exception 
     **/  

public static void zipToFile(String sourceFile, String toFolder)  

            throws Exception {  
        String toDisk = toFolder;// 接收解压后的存放路径  
        ZipFile zfile = new ZipFile(sourceFile);// 连接待解压文件  创建待解压文件对象
        Enumeration zList = zfile.entries();// 得到zip包里的所有元素  
        ZipEntry ze = null;  
        byte[] buf = new byte[1024];  
        while (zList.hasMoreElements()) {  
            ze = (ZipEntry) zList.nextElement(); //遍历压缩包中的所有元素 
            if (ze.isDirectory()) { //如果当前元素是文件夹,跳出本次循环。
//              log.info("打开zip文件里的文件夹:" + ze.getName() + "skipped...");  
                continue;  
            }  
            OutputStream outputStream = null;  //创建输出流对象
            InputStream inputStream = null;  //创建输入流对像
            try {  
                // 以ZipEntry为参数得到一个InputStream,并写到OutputStream中  
                outputStream = new BufferedOutputStream(new FileOutputStream(  
                        getRealFileName(toDisk, ze.getName()))); //创建写入字符流对象(参数:写入的文件夹 toDisk,写入的文件名称 ze.getName())
                inputStream = new BufferedInputStream(zfile.getInputStream(ze)); //当前元素转为输入流对象(待输入) 
                int readLen = 0;  
                while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {  //循环读取输入流(每次1024字节)
                    outputStream.write(buf, 0, readLen);  //写入文件
                }  
                inputStream.close();  //完毕后关闭输入,输出流。
                outputStream.close();  
            } catch (Exception e) {  
//              log.info("解压失败:" + e.toString());  
                throw new IOException("解压失败:" + e.toString());  
            } finally {  
                if (inputStream != null) {  
                    try {  
                        inputStream.close();  
                    } catch (IOException ex) {  
  
                    }  
                }  
                if (outputStream != null) {  
                    try {  
                        outputStream.close();  
                    } catch (IOException ex) {  
                        ex.printStackTrace();  
                    }  
                }  
                inputStream = null;  
                outputStream = null;  
            }  
  
        }  
        zfile.close();  
    }  

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值