资产文件夹中的android copy database

时间:2015-06-15 11:33:17

标签: java android sqlite

我无法将数据库从assets文件夹复制到数据库文件夹。当用户启动应用程序时,我检查数据库是否不存在,如果为true,则复制数据库。

我的代码在哪里:

    private void CopyDatabaseIfNotExists() {

        dbName = "quizdb.db";

        File f = getDatabasePath(dbName);
        if (f.exists())
            return;

        System.out.println("db missing");

        try {

            InputStream mInputStream = getAssets().open(dbName);

            OutputStream mOutputStream = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = mInputStream.read(buffer)) > 0) {
                mOutputStream.write(buffer, 0, length);
            }
            mOutputStream.flush();
            mOutputStream.close();
            mInputStream.close();

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我收到了这个错误:

06-15 12:29:04.882  25037-25037/com.ex.example W/System.err﹕ java.io.FileNotFoundException: /data/data/com.ex.example/databases/quizdb.db: open failed: ENOENT (No such file or directory)

我已经尝试过寻找解决方案,但无法找到。有人可以帮帮我吗?谢谢,对不起我的英语。

2 个答案:

答案 0 :(得分:1)

试试这个...它为我工作.. !!并且您确定已将数据库文件放在assets文件夹中。!!

 private void copyDataBase() throws IOException {
    InputStream is = myContext.getAssets().open(DB_NAME);
    // Log.v("Tag assets",is.toString());
    String outFileName = DB_PATH + DB_NAME;
    OutputStream out = new FileOutputStream(outFileName);
    Log.v("Tag assets", out.toString());
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0) {
        // Log.v("Tag",out.toString());
        out.write(buffer, 0, length);
        // Log.v("Tag",out.toString());
    }
    // Log.v("Tag","Database created");
    is.close();
    out.flush();
    out.close();      

}

答案 1 :(得分:1)

当文件不存在时,

FileOutputStream会抛出此异常并且无法创建。我之前遇到过这个问题并设法通过在openOrCreateDatabase

之前首先调用Context对象(或SQLiteDatabase类)的OutputStream mOutputStream = new FileOutputStream(f);方法来解决它