Android 拷贝数据库文件

来源:互联网 发布:js获取li的name属性 编辑:程序博客网 时间:2024/05/20 11:27


        做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)
如果该文件没有,则拷贝,如果有,不拷贝