拷贝assets下的数据库至data/data目录及使用SQLiteDatabase 访问

来源:互联网 发布:盖革计数器 淘宝 编辑:程序博客网 时间:2024/05/29 04:57

1、拷贝assets下的数据库至data/data目录

    /**     * 拷贝assets下的数据库至data/data目录     */    private void copyDb(String dbName) {        File filesDir = getFilesDir();// 获取data/data/files目录的文件夹        System.out.println("filesDir:" + filesDir.getAbsolutePath());        File outFile = new File(filesDir, dbName);        if (outFile.exists()) {//确保只复制一次            System.out.println("数据库" + dbName + "已经存在,无需拷贝!");            return;        }        FileOutputStream out = null;        InputStream in = null;        try {            out = new FileOutputStream(outFile);            in = getAssets().open(dbName);            int len = 0;            byte[] buffer = new byte[1024];            while ((len = in.read(buffer)) != -1) {                out.write(buffer, 0, len);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                out.close();                in.close();            } catch (Exception e) {                e.printStackTrace();            }        }        System.out.println("拷贝数据库" + dbName + "成功!");    }

2、SQLiteDatabase 访问方法:

private static final String PATH = "data/data/com.xxx.xxx/files/xxxx.db";SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH, null,SQLiteDatabase.OPEN_READONLY);//通过只读方式打开数据库, 注意:只能访问data/data目录下的数据库文件,可以在闪屏页面,拷贝数据库至data/data目录Cursor cursor = database.rawQuery("select location from table where id= (select XXX from table where id = ?)","XX");if (cursor.moveToFirst()) {    System.out.println("有值");   }cursor.close();
0 0
原创粉丝点击