歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 拷貝數據庫文件

Android 拷貝數據庫文件

日期:2017/3/1 10:17:26   编辑:Linux編程

做Android開發時,有時並不一定要創建數據庫然後插入數據的過程。譬如,需要提供一個大數據量資源的搜索功能。像號碼歸屬地,城市列表,ip歸屬地等。此時如果鍵數據庫,再將數據一條一條insert到數據庫中,不僅耗時,占用資源,有時還會導入錯誤。最好的方法是將數據庫建好,數據insert好,並將該beifen.db文件放在raw(如果沒有,在res目錄下建一個)目錄下。在創建數據庫時,直接將該文件拷貝到databases目錄下:

DATABASES_DIR="/data/data/yourpackagedir/databases", DATABASE_NAME="beifen.db"。詳細見代碼:

  1. public static synchronized CityDBHelper getInstance(Context context) {
  2. copyDatabaseFile(context, true);
  3. if(mDatabase == null){
  4. mDatabase = new CityDBHelper(context);
  5. }
  6. return mDatabase;
  7. }
  8. public static void copyDatabaseFile(Context context, boolean isfored) {
  9. Log.v(TAG, "--------------------------------copyDatabaseFile-");
  10. File dir = new File(DATABASES_DIR);
  11. if (!dir.exists() || isfored) {
  12. try {
  13. dir.mkdir();
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. File dest = new File(dir, DATABASE_NAME);
  19. if(dest.exists() && !isfored){
  20. return ;
  21. }
  22. try {
  23. if(dest.exists()){
  24. dest.delete();
  25. }
  26. dest.createNewFile();
  27. InputStream in = context.getResources().openRawResource(R.raw.beifen);
  28. int size = in.available();
  29. byte buf[] = new byte[size];
  30. in.read(buf);
  31. in.close();
  32. FileOutputStream out = new FileOutputStream(dest);
  33. out.write(buf);
  34. out.close();
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. }
  38. }

如果這樣還不放心,可以在運行ContentProvider的query(一般拷貝數據庫都是用於查詢的)時,做一次拷貝檢測

  1. copyDatabaseFile(context, false)

如果該文件沒有,則拷貝,如果有,不拷貝

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved