Android 拷贝数据库文件


做Android开发时,有时并不一定要创建数据库然后插入数据的过程。譬如,需要提供一个大数据量资源的搜索功能。像号码归属地,城市列表,ip归属地等。此时如果键数据库,再将数据一条一条insert到数据库中,不仅耗时,占用资源,有时还会导入错误。最好的方法是将数据库建好,数据insert好,并将该beifen.db文件放在raw(如果没有,在res目录下建一个)目录下。在创建数据库时,直接将该文件拷贝到databases目录下:

DATABASES_DIR="/data/data/yourpackagedir/databases", DATABASE_NAME="beifen.db"。详细见代码:

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

如果这样还不放心,可以在运行ContentProvider的query(一般拷贝数据库都是用于查询的)时,做一次拷贝检测

  1. copyDatabaseFile(context, false)  

如果该文件没有,则拷贝,如果有,不拷贝

更多Android相关信息见Android 专题页面 http://www.bkjia.com/topicnews.aspx?tid=11

相关内容