读取assets目录下的数据库文件

先从assets目录下读取文件到sd卡中
public static String CopySqliteFileFromRawToDatabases(String SqliteFileName) throws IOException {

    // 第一次运行应用程序时,加载数据库到data/data/当前包的名称/database/<db_name>

    File dir = new File("data/data/" + MyApplication.getContext().getPackageName() + "/databases");
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();
    }

    File file = new File(dir, SqliteFileName);
    InputStream inputStream = null;
    OutputStream outputStream = null;

    //通过IO流的方式,将assets目录下的数据库文件,写入到SD卡中。
    if (!file.exists()) {
        try {
            file.createNewFile();
            inputStream = MyApplication.getContext().getClass().getClassLoader().getResourceAsStream("assets/" + SqliteFileName);
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }


        } catch (IOException e) {
            e.printStackTrace();

        } finally {

            if (outputStream != null) {

                outputStream.flush();
                outputStream.close();

            }
            if (inputStream != null) {
                inputStream.close();
            }

        }

    }

    return file.getPath();

}
然后通过sql语句进行操控
/**
 * 操作数据库进行查询
 *
 * @return
 */
private List<LoginBean> getProvincesFromSQLite() {
    //数据库所在SD卡路径
    String path = "data/data/" + MyApplication.getContext().getPackageName() + "/databases/linepower.sqlite";
    SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.CONFLICT_NONE);
    //查询数据
    Cursor cursor = db.rawQuery("select description from exception values;", null);
    List<LoginBean> list = new ArrayList<>();
    LoginBean loginBean = null;
    while (cursor.moveToNext()) {
        String description = cursor.getString(cursor.getColumnIndex("description"));
        loginBean = new LoginBean(description);
        list.add(loginBean);
    }
    return list;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值