Android 復制數據庫文件
做android開發時,有時并不一定要創建數據庫然后插入數據的過程。譬如,需要提供一個大數據量資源的搜索功能。像號碼歸屬地,城市列表,ip歸屬地 等。此時如果鍵數據庫,再將數據一條一條insert到數據庫中,不僅耗時,占用資源,有時還會導入錯誤。最好的方法是將數據庫建好,數據insert 好,并將該beifen.db文件放在raw(如果沒有,在res目錄下建一個)目錄下。在創建數據庫時,直接將該文件拷貝到databases目錄 下:DATABASES_DIR="/data/data/yourpackagedir/databases", DATABASE_NAME="beifen.db"。詳細見代碼:
public static synchronized CityDBHelper getInstance(Context context) { copyDatabaseFile(context, true); if(mDatabase == null){ mDatabase = new CityDBHelper(context); } return mDatabase; } public static void copyDatabaseFile(Context context, boolean isfored) { Log.v(TAG, "--------------------------------copyDatabaseFile-"); File dir = new File(DATABASES_DIR); if (!dir.exists() || isfored) { try { dir.mkdir(); } catch (Exception e) { e.printStackTrace(); } } File dest = new File(dir, DATABASE_NAME); if(dest.exists() && !isfored){ return ; } try { if(dest.exists()){ dest.delete(); } dest.createNewFile(); InputStream in = context.getResources().openRawResource(R.raw.beifen); int size = in.available(); byte buf[] = new byte[size]; in.read(buf); in.close(); FileOutputStream out = new FileOutputStream(dest); out.write(buf); out.close(); } catch (Exception e) { e.printStackTrace(); } }
如果這樣還不放心,可以在運行ContentProvider的query(一般拷貝數據庫都是用于查詢的)時,做一次拷貝檢測
copyDatabaseFile(context, false)如果該文件沒有,則拷貝,如果有,不拷貝
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!