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

来源:互联网 发布:js filter 编辑:程序博客网 时间:2024/05/21 10:18
先从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