1. 程式人生 > >java解壓zip文件至指定文件夾

java解壓zip文件至指定文件夾

ava tel exceptio 失敗 ppr mark roc types EDA

前面,筆者講到。如何把文件打包為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文件至指定文件夾