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

Android 將壓縮資料庫檔案解壓並拷貝到安裝目錄的方法

編輯:關於 Android 程式設計

本文分享一個實用技巧:如何把打包好的壓縮檔(例如預置的資料庫 zip)在首次執行時解壓並釋放到 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(); } 

整體邏輯是先用 AssetManager 讀取 assets 裡的 zip 檔,透過 ZipInputStream 逐一取出每個條目,再以串流的方式寫入 App 私有目錄。這樣一來,預先打包好的初始資料就能在首次啟動時完成初始化。

希望本文所述能對大家的 Android 開發有所幫助。

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