Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 解壓縮實作:ZIP 含資料夾與不含資料夾的兩種寫法

編輯:關於 Android 程式設計

Android 上處理 ZIP 檔用的是 Java 標準的 java.util.zip 套件,核心是 ZipFile 與 ZipEntry。實作時要留意兩件事:目錄層級的重建,以及中文檔名的編碼問題。

寫法一:壓縮檔內含資料夾結構

/**
 * 解壓縮含有資料夾的壓縮檔
 *
 * @param zipFile    來源 ZIP 檔
 * @param folderPath 解壓縮目標目錄
 * @throws ZipException
 * @throws IOException
 */
public void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
    File desDir = new File(folderPath);
    if (!desDir.exists()) {
        desDir.mkdirs(); // 建立目標目錄
    }

    ZipFile zf = new ZipFile(zipFile);
    for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = ((ZipEntry) entries.nextElement());

        if (entry.isDirectory()) {
            String tmpStr = folderPath + File.separator + entry.getName();
            tmpStr = new String(tmpStr.getBytes("8859_1"), "GB2312");
            File folder = new File(tmpStr);
            folder.mkdirs();
        } else {
            InputStream is = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            // 轉換編碼,避免中文亂碼
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                desFile.createNewFile(); // 建立目標檔案
            }
            OutputStream os = new FileOutputStream(desFile);
            byte[] buffer = new byte[1024];
            int realLength;
            while ((realLength = is.read(buffer)) > 0) {
                os.write(buffer, 0, realLength);
                os.flush();
            }
            is.close();
            os.close();
        }
    }
    zf.close();
}

這個版本會判斷 entry.isDirectory():遇到目錄條目就建立對應資料夾,遇到檔案才走讀寫流程。因為它把資料夾層級還原出來,所以寫檔前不需要額外處理父目錄。

寫法二:壓縮檔內不含資料夾

/**
 * 解壓縮不含資料夾的壓縮檔
 *
 * @param zipFile    來源 ZIP 檔
 * @param folderPath 解壓縮目標目錄
 * @throws ZipException
 * @throws IOException
 */
public void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
    File desDir = new File(folderPath);
    if (!desDir.exists()) {
        desDir.mkdirs(); // 建立目標目錄
    }

    ZipFile zf = new ZipFile(zipFile);
    for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = ((ZipEntry) entries.nextElement());
        InputStream is = zf.getInputStream(entry);
        String str = folderPath + File.separator + entry.getName();
        // 轉換編碼,避免中文亂碼
        str = new String(str.getBytes("8859_1"), "GB2312");
        File desFile = new File(str);
        if (!desFile.exists()) {
            File fileParentDir = desFile.getParentFile();
            if (!fileParentDir.exists()) {
                fileParentDir.mkdirs(); // 建立目標檔案的父目錄
            }
            desFile.createNewFile(); // 建立目標檔案
        }
        OutputStream os = new FileOutputStream(desFile);
        byte[] buffer = new byte[1024];
        int realLength;
        while ((realLength = is.read(buffer)) > 0) {
            os.write(buffer, 0, realLength);
            os.flush();
        }
        is.close();
        os.close();
    }
    zf.close();
}

這版不判斷是否為目錄,而是靠 desFile.getParentFile() 補建父目錄。實務上這種寫法更通用,因為它同時能處理有層級與沒層級的壓縮檔,建議優先採用。

關於那段編碼轉換

new String(str.getBytes("8859_1"), "GB2312") 這行是個常見但容易誤解的寫法。Java 的 ZipFile 在讀取 entry 名稱時,若壓縮端未標註 UTF-8 旗標,會以 ISO-8859-1 解讀原始位元組。這行程式把名稱「還原」回位元組,再以 GB2312 重新解碼,就能正確顯示繁體中文或簡體中文檔名。

要注意的是:編碼必須與壓縮時一致。若來源是 UTF-8 打包的(例如 macOS 或新版 7-Zip 預設),硬轉 GB2312 反而會產生亂碼。較穩妥的做法是先判斷 ZipEntry 的 UTF-8 旗標,或直接改用 ZipInputStream 搭配 Charset 參數(Java 7 以後 ZipFile 建構子已支援指定 charset)。

三個應該補上的防護

原始寫法在正式專案中還缺少幾項保護,建議補齊:

  • 路徑穿越攻擊:惡意壓縮檔可能在 entry 名稱中放入 ../../,解壓後檔案會寫到目標目錄之外。解壓前應檢查 desFile.getCanonicalPath() 是否以 desDir.getCanonicalPath() 開頭,不符合就跳過。
  • 串流關閉:InputStream 與 OutputStream 應該放在 try-with-resources 或 finally 中關閉,避免例外時檔案描述符洩漏。
  • 寫入後確實 flush:目前的迴圈每次都 flush,效能不佳。建議寫完再一次 flush 並 close 即可。

另外,解壓縮屬於 I/O 密集操作,在 Android 上務必放到背景執行緒(例如 ExecutorService 或 Kotlin 的 Dispatchers.IO),否則會觸發 NetworkOnMainThread 之外的主執行緒卡頓與 ANR 問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved