Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

把 assets 裡的壓縮檔解開到 App 資料目錄

編輯:Android 開發實例

有些專案會預先把一份壓縮過的資源(字型、初始資料、離線包)放在 assets 裡,App 第一次啟動時再解開到 files 目錄。與其一個一個檔案寫入,直接把整個 zip 串流讀開會乾淨很多。

下面的方法示範了完整的流程:從 AssetManager 開啟 zip,用 ZipInputStream 逐筆取出 entry,再用 openFileOutput() 寫進 App 私有的資料目錄。

 public void copyZip2DataDirectory(Context context) throws IOException { FileOutputStream outputStream = null; AssetManager assetManager = context.getAssets(); InputStream inputStream = assetManager.open("test.zip"); ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry entry = null; while ((entry = zis.getNextEntry()) != null) { outputStream = context.openFileOutput(entry.getName(), Context.MODE_PRIVATE); byte[] buffer = new byte[2 * 1024]; int len = -1; while ((len = zis.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); } zis.close(); inputStream.close(); }

程式碼在做什麼

整體是標準的「串流對串流」複製:getNextEntry() 每次推進到下一個檔案,內層迴圈以 2KB 緩衝區把內容一塊塊搬過去。因為全程使用串流,記憶體用量與檔案大小無關,這點在處理幾十 MB 的資源包時特別重要。

這段程式碼值得改良的地方

能跑,但直接搬進專案前,建議補上幾件事:

1. 用 try-with-resources 確保關閉。目前若中途拋出 IOException,outputStream 與 zis 都不會被關閉,長久下來會耗盡檔案描述符。

 public void copyZip2DataDirectory(Context context) throws IOException { try (AssetManager am = context.getAssets(); InputStream in = am.open("test.zip"); ZipInputStream zis = new ZipInputStream(in)) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) continue; try (FileOutputStream out = context.openFileOutput(entry.getName(), Context.MODE_PRIVATE)) { byte[] buffer = new byte[8 * 1024]; int len; while ((len = zis.read(buffer)) != -1) { out.write(buffer, 0, len); } } } } }

2. 正視 Zip Slip 風險。如果壓縮檔來源不完全可控(例如從網路下載後再解開),entry.getName() 可能包含 ../ 這類路徑跳脫字元,把檔案寫到 App 目錄之外。更何況 openFileOutput() 不支援子路徑,一旦 entry 帶有目錄結構就會直接失敗。比較穩健的做法是解到自己計算出來的絕對路徑,並驗證結果仍位於預期目錄底下:

 File target = new File(context.getFilesDir(), entry.getName()); if (!target.getCanonicalPath().startsWith(context.getFilesDir().getCanonicalPath())) { throw new IOException("Bad zip entry: " + entry.getName()); }

3. 加上「是否已解壓」的判斷。每次啟動都重跑一次解壓很浪費。實務上會檢查目標目錄裡的版本標記檔或 sharedPreferences 裡的版本號,只有在 App 升級、資源版本改變時才重新解開。

4. 搬移到背景執行緒。檔案 I/O 不能放在主執行緒,會觸發 NetworkOnMainThreadException 的同類檢查(StrictMode 下的 DiskRead/DiskWrite 警告),也會造成啟動畫面卡住。用 ExecutorService 或協程執行,完成後再回主執行緒更新 UI。

小結

解壓 zip 到 App 資料目錄是個很實用的小技巧,特別適合首次啟動時鋪初始資料。掌握「串流複製省記憶體」、「路徑驗證防 Zip Slip」、「版本判斷避免重複工作」、「背景執行不阻塞 UI」這四點,這段程式碼就能安心用在正式專案裡。

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