Zip文件和RAR文件解壓

直接上工具類:java

package com.ksource.pwlp.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

public class ZipAndRarUnpackUtil {

    /**
     * 解壓zip
     *
     * @param zipFile
     * @param descDir
     * @throws Exception
     */
    public void unZipFiles(File zipFile, String descDir) throws Exception {
        System.out.println("******************解壓開始********************");
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile 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);
            String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
            // 判斷路徑是否存在,不存在則建立文件路徑
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判斷文件全路徑是否爲文件夾,若是是上面已經上傳,不須要解壓
            if (new File(outPath).isDirectory()) {
                continue;
            }
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            if ((zipEntryName.trim().lastIndexOf("/")) == -1) {

            }
            in.close();
            out.close();
        }
        System.out.println("******************解壓完畢********************");
    }
    
    
    /**  
     * 解壓rar格式壓縮包。  
     * 對應的是java-unrar-0.3.jar,可是java-unrar-0.3.jar又會用到commons-logging-1.1.1.jar  
     */   
    public void unRarFiles(File rarFile, String descDir) throws Exception{    
        Archive a = null;    
        FileOutputStream fos = null;    
        try{    
            a = new Archive(rarFile);    
            FileHeader fh = a.nextFileHeader();    
            while(fh!=null){    
                if(!fh.isDirectory()){    
                    //1 根據不一樣的操做系統拿到相應的 destDirName 和 destFileName    
                    //String compressFileName = fh.getFileNameString().trim();    
                    String compressFileName = fh.getFileNameW().trim();                 
                    if(!existZH(compressFileName)){                    
                        compressFileName = fh.getFileNameString().trim();                 
                    } 
                    String destFileName = "";    
                    String destDirName = "";    
                    //非windows系統    
                    if(File.separator.equals("/")){    
                        destFileName = descDir + compressFileName.replaceAll("\\\\", "/");    
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));    
                    //windows系統     
                    }else{    
                        destFileName = descDir + compressFileName.replaceAll("/", "\\\\");    
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));    
                    }    
                    //2建立文件夾    
                    File dir = new File(destDirName);    
                    if(!dir.exists()||!dir.isDirectory()){    
                        dir.mkdirs();    
                    }    
                    //3解壓縮文件    
                    fos = new FileOutputStream(new File(destFileName));    
                    a.extractFile(fh, fos);    
                    fos.close();    
                    fos = null;    
                }    
                fh = a.nextFileHeader();    
            }    
            a.close();    
            a = null;    
        }catch(Exception e){    
            throw e;    
        }finally{    
            if(fos!=null){    
                try{fos.close();fos=null;}catch(Exception e){e.printStackTrace();}    
            }    
            if(a!=null){    
                try{a.close();a=null;}catch(Exception e){e.printStackTrace();}    
            }    
        }    
    }    
    
    
    public static boolean existZH(String str) {  
        String regEx = "[\\u4e00-\\u9fa5]";  
        Pattern p = Pattern.compile(regEx);  
        Matcher m = p.matcher(str);  
        while (m.find()) {  
            return true;  
        }  
        return false;  
    }  
    
    /**
     * 文件夾遍歷
     * @param path
     * @throws Exception
     */
    public void traverse(String path,String parent_id) throws Exception {
        System.out.println("path---->" + path);
        File file = new File(path);
        Map<String, Object> map = new HashMap<String, Object>();
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件夾是空的!");
                return;
            } else {
                String k_id = UUID.randomUUID().toString();

                for (File file2 : files) {
                    if (file2.isDirectory()) {//文件夾

                        traverse(file2.getAbsolutePath(),parent_id);
                        parent_id =  k_id;
                    } else if (file2.isFile()){//文件

                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
    
    
    /**
     * 採用命令行方式解壓文件(rar解壓會出現版本不一致形成的解壓失敗,因此用命令方式解壓更穩妥)
     * @param zipFile 壓縮文件
     * @param destDir 解壓結果路徑
     * @param cmdPath WinRAR.exe的路徑,也能夠在代碼中寫死
     * @return
     */
    public void realExtract(File rarFile, String destDir) {
        // 解決路徑中存在/..格式的路徑問題
        destDir = new File(destDir).getAbsoluteFile().getAbsolutePath();
        while(destDir.contains("..")) {
            String[] sepList = destDir.split("\\\\");
            destDir = "";
            for (int i = 0; i < sepList.length; i++) {
                if(!"..".equals(sepList[i]) && i < sepList.length -1 && "..".equals(sepList[i+1])) {
                    i++;
                } else {
                    destDir += sepList[i] + File.separator;
                }
            }
        }
        String path = System.getProperty("user.dir");
        boolean bool = false;
        if (rarFile.exists()) {
            // 開始調用命令行解壓,參數-o+是表示覆蓋的意思
            String cmdPath = path+"\\metadata\\7zip\\7z.exe";
            cmdPath = cmdPath .replaceAll(" ", "\" \"");//全部空格都替換成帶有雙引號的空格
            String cmd = cmdPath + " x " + rarFile.getPath() + " -o" + destDir; 
            System.out.println(cmd);
            try {
                Process proc = Runtime.getRuntime().exec(cmd);
                if (proc.waitFor() != 0) {
                    if (proc.exitValue() == 0) {
                        bool = false;
                    }
                } else {
                    bool = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("解壓" + (bool ? "成功" : "失敗"));
        }
    }
}
realExtract方法中的7z壓縮包路徑cmdPath是先將7z壓縮包安裝完以後拷貝安裝路徑到項目中去,而後運用cmd命令執行7z壓縮包
7z壓縮包下載地址:https://www.7-zip.org/a/7z1900-x64.exe
相關文章
相關標籤/搜索