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

版权声明:转载请注明出处! https://blog.csdn.net/ziyejinwei1994/article/details/51777310
先从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;
}

猜你喜欢

转载自blog.csdn.net/ziyejinwei1994/article/details/51777310