码迷,mamicode.com
首页 > 编程语言 > 详细

java解压zip文件至指定文件夹

时间:2018-09-09 16:05:15      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:proc   types   stack   不可   sub   md5   warnings   more   结果   

前面,笔者讲到。如何把文件打包为zip包,那么反过来怎么把zip文件包解压为正常文件呢?把zip包解压为正常文件包,要比把文件打包为zip简单一点。因为存在多级文件的压缩,却不存在多级文件的解压缩。也就是说,压缩时,你要把所有文件都塞到压缩包里。而解压缩只需要解压一级,压缩包里面的压缩文件则不必理会。
直接上代码喽:

    /**
     * 解压文件
     * @param zipPath 要解压的目标文件
     * @param descDir 指定解压目录
     * @return 解压结果:成功,失败
     */
    @SuppressWarnings("rawtypes")
    public boolean decompressZip(String zipPath, String descDir) {
        File zipFile = new File(zipPath);
        boolean flag = false;
        File pathFile = new File(descDir);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        ZipFile zip = null;
        try {
            zip = new ZipFile(zipFile, Charset.forName("gbk"));//防止中文目录,乱码
            for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
                ZipEntry entry = (ZipEntry)entries.nextElement();
                String zipEntryName = entry.getName();
                InputStream in = zip.getInputStream(entry);
                //指定解压后的文件夹+当前zip文件的名称
                String outPath = (descDir+zipEntryName).replace("/", File.separator);
                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
                if(!file.exists()){
                    file.mkdirs();
                }
                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if(new File(outPath).isDirectory()){
                    continue;
                }
                //保存文件路径信息(可利用md5.zip名称的唯一性,来判断是否已经解压)
                System.err.println("当前zip解压之后的路径为:" + outPath);
                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[2048];
                int len;
                while((len=in.read(buf1))>0){
                    out.write(buf1,0,len);
                }
                in.close();
                out.close();
            }
            flag = true;
            //必须关闭,要不然这个zip文件一直被占用着,要删删不掉,改名也不可以,移动也不行,整多了,系统还崩了。
            zip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

找个例子实现一下:
就你了!
技术分享图片

调用:

                String deal_zip = "C:\\20180909.zip";
                String agter_zip = "D:\\red_ant_file";//解压完塞到这里吧
                boolean is_success = AllServiceIsHere.decompressZip(deal_zip, agter_zip);
                if(is_success) {
                    System.err.println("恭喜你,解压成功!");
                }else {
                    System.err.println("sorry, you failed!");
                }

走你!

技术分享图片

嗯嗯,达到了我所要求的。赶集去喽!
技术分享图片
技术分享图片

技术分享图片

java解压zip文件至指定文件夹

标签:proc   types   stack   不可   sub   md5   warnings   more   结果   

原文地址:http://blog.51cto.com/13479739/2172847

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!