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

善用 Android 內建的 GZIP,輕鬆完成字串壓縮與解壓

編輯:關於 Android 程式設計

專案裡遇到需要保存壓縮資料的場景時,不必急著引入第三方庫——java.util.zip 已經足夠。我寫了一個小工具類,可以直接把字串壓成檔案,省下「先落地成檔、再讀回壓縮」的來回開銷:

/**
 * 壓縮與解壓縮工具
 */
public class ZipUtil {

    /**
     * 將字串壓縮為檔案
     * @param str  要壓縮的字串
     * @param path 輸出路徑
     */
    public static void compress(String str, String path) throws IOException {
        if (str == null || str.length() <= 0) {
            return;
        }
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        GZIPOutputStream gzip = new GZIPOutputStream(fileOutputStream);
        gzip.write(str.getBytes("utf-8"));
        gzip.close();
        fileOutputStream.close();
    }

    /**
     * 解壓縮檔案內容
     * @param context 上下文,用於讀取提示字串資源
     * @param path    檔案路徑
     * @return 解出的字串;失敗時回傳 null
     */
    public static String unCompress(Context context, String path) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                return context.getResources().getString(R.string.FileNotExits);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            FileInputStream fileInputStream = new FileInputStream(path);
            GZIPInputStream gzip = new GZIPInputStream(fileInputStream);
            byte[] buffer = new byte[256];
            int n;
            // 逐段把解壓後的資料寫入記憶體
            while ((n = gzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

使用上的幾點提醒

GZIP 不是 ZIP。GZIPOutputStream 處理的是單一資料流的壓縮,適合字串、設定檔這類單一內容;若需求是多檔案打包,則該改用 ZipOutputStream 搭配 ZipEntry。

字元編碼要一致。壓縮端與解壓端務必都指定 UTF-8,否則中文很容易出現亂碼。

記得關流。範例為求簡潔直接 close;實務上建議改用 try-with-resources,即使中途拋例外也能確保檔案描述符被釋放。

緩衝區大小。256 bytes 偏小,會增加迴圈次數,可視資料量調整到 1024 或 4096。

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