Java代碼解壓RAR/ZIP檔案__Java

來源:互聯網
上載者:User

pom.xml

<!-- 匯入zip解壓包 --><dependency>    <groupId>ant</groupId>    <artifactId>ant</artifactId>    <version>1.6.5</version></dependency><!-- 匯入rar解壓包 --><dependency>    <groupId>com.github.junrar</groupId>    <artifactId>junrar</artifactId>    <version>0.7</version></dependency>
FileUnZipRar.zipRarToFile(fileName, uploadDir + "temp\\" + fileName, uploadDir + "\\staticPage")

FileUnZipRar.java

import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;import java.io.*;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;import com.github.junrar.Archive;import com.github.junrar.rarfile.FileHeader;public class FileUnZipRar {    /**     * 解壓     *     * @param sourceFile     * @param toFolder     */    public static String zipRarToFile(String fileName, String sourceFile, String toFolder) throws Exception {        int pos = fileName.lastIndexOf(".");        String extName = fileName.substring(pos + 1).toLowerCase();        File pushFile = new File(sourceFile);        File descFile = new File(toFolder);        if (!descFile.exists()) {            descFile.mkdirs();        }        //解壓目的檔案        String descDir = toFolder + "\\" + fileName.substring(0, pos) + "\\";        //開始解壓zip        if (extName.equals("zip")) {            FileUnZipRar.unZipFiles(pushFile, descDir);        } else if (extName.equals("rar")) {            //開始解壓rar            FileUnZipRar.unRarFile(pushFile.getAbsolutePath(), descDir);        }        //驗證檔案夾中是否含有index.html檔案,此功能可去掉        String linkUrl = checkIndexHtml(descDir);        if (!StringUtil.isNotNullStr(linkUrl)) {            throw new Exception("檔案中缺少index.html");        }        return linkUrl;    }    /**     * 檢查是否有index.html     *     * @param strPath     * @return     */    public static String checkIndexHtml(String strPath) {        String linkUrl = null;        List<File> filelist = new ArrayList<File>();        List<File> files = getFileList(filelist, strPath); // 該檔案目錄下檔案全部放入數組        if (CollectionUtil.isNotEmpty(files)) {            for (int i = 0; i < files.size(); i++) {                String fileName = files.get(i).getName();                if ("index.html".equals(fileName)) { // 判斷是否有index.html                    String path = files.get(i).getPath();                    int pos = path.lastIndexOf("upmall");                    linkUrl = path.substring(pos + 7, path.length());                    break;                }            }        }        return linkUrl;    }    /**     * 擷取所有檔案     *     * @param filelist     * @param strPath     * @return     */    public static List<File> getFileList(List<File> filelist, String strPath) {        File dir = new File(strPath);        File[] files = dir.listFiles(); // 該檔案目錄下檔案全部放入數組        if (files != null) {            for (int i = 0; i < files.length; i++) {                String fileName = files[i].getName();                if (files[i].isDirectory()) { // 判斷是檔案還是檔案夾                    getFileList(filelist, files[i].getAbsolutePath()); // 擷取檔案絕對路徑                } else {                    filelist.add(files[i]);                    continue;                }            }        }        return filelist;    }    /**     * 解壓到指定目錄     *     * @param zipPath     * @param descDir     * @author     */    public static void unZipFiles(String zipPath, String descDir) throws IOException {        unZipFiles(new File(zipPath), descDir);    }    /**     * 解壓檔案到指定目錄     *     * @param zipFile     * @param descDir     * @author isea533     */    @SuppressWarnings("rawtypes")    public static void unZipFiles(File zipFile, String descDir) throws IOException {        File pathFile = new File(descDir);        if (!pathFile.exists()) {            pathFile.mkdirs();        }        ZipFile zip = new ZipFile(zipFile);        for (Enumeration entries = zip.getEntries(); 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;            }            //輸出檔案路徑資訊            System.out.println(outPath);            OutputStream out = new FileOutputStream(outPath);            byte[] buf1 = new byte[1024];            int len;            while ((len = in.read(buf1)) > 0) {                out.write(buf1, 0, len);            }            in.close();            out.close();        }    }    /**     * 根據原始rar路徑,解壓到指定檔案夾下.     *     * @param srcRarPath       原始rar路徑     * @param dstDirectoryPath 解壓到的檔案夾     */    public static void unRarFile(String srcRarPath, String dstDirectoryPath) {        if (!srcRarPath.toLowerCase().endsWith(".rar")) {            System.out.println("非rar檔案。");            return;        }        File dstDiretory = new File(dstDirectoryPath);        if (!dstDiretory.exists()) {// 目標目錄不存在時,建立該檔案夾            dstDiretory.mkdirs();        }        Archive a = null;        try {            a = new Archive(new File(srcRarPath));            if (a != null) {                a.getMainHeader().print(); // 列印檔案資訊.                FileHeader fh = a.nextFileHeader();                while (fh != null) {                    if (fh.isDirectory()) { // 檔案夾                        File fol = new File(dstDirectoryPath + File.separator                                + fh.getFileNameString());                        fol.mkdirs();                    } else { // 檔案                        File out = new File(dstDirectoryPath + File.separator                                + fh.getFileNameString().trim());                        try {// 之所以這麼寫try,是因為萬一這裡面有了異常,不影響繼續解壓.                            if (!out.exists()) {                                if (!out.getParentFile().exists()) {// 相對路徑可能多級,可能需要建立父目錄.                                    out.getParentFile().mkdirs();                                }                                out.createNewFile();                            }                            FileOutputStream os = new FileOutputStream(out);                            a.extractFile(fh, os);                            os.close();                        } catch (Exception ex) {                            ex.printStackTrace();                        }                    }                    fh = a.nextFileHeader();                }                a.close();            }        } catch (Exception e) {            e.printStackTrace();        }    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.