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

Android 將 raw 文件夾中的數據庫導入應用的實現

編輯:關於 Android 程式設計

先看一道常見的面試題:如何將 SQLite 數據庫(如 dictionary.db)與 apk 一起發布?

答案很簡單:把該文件放在 /res/raw 目錄下即可。res\raw 目錄中的文件不會被壓縮,可以直接提取,並且會生成資源 id。

那麼,如何把 raw 目錄下的數據庫導入到已安裝應用的 databases 目錄呢?關鍵思路是:先確保目標目錄與文件存在,再透過 openRawResource 讀取原始資源流,最後寫入到應用私有目錄。

public void imporDatabase() {
  //存放數據庫的目錄
  String dirPath = "/data/data/com.hkx.wan/databases";
  File dir = new File(dirPath);
  if (!dir.exists()) { dir.mkdir(); }
  //數據庫文件
  File file = new File(dir, "abc.db");
  try {
   if (!file.exists()) { file.createNewFile(); }
   //加載需要導入的數據庫
   InputStream is = this.getApplicationContext().getResources().openRawResource(R.raw.db_weather);
   FileOutputStream fos = new FileOutputStream(file);
   byte[] buffere = new byte[is.available()];
   is.read(buffere);
   fos.write(buffere);
   is.close();
   fos.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
}

這段代碼展示了資源拷貝的基本流程:定位目錄 → 讀取 raw 資源 → 寫入目標文件。實際項目中,通常會在首次啟動時判斷數據庫是否已存在,若不存在再執行導入,避免重複覆蓋用戶數據。

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