繁体   English   中英

android从assets文件夹复制数据库

[英]android copy database from assets folder

我无法将数据库从资产文件夹复制到数据库文件夹。 当用户启动应用程序时,我检查数据库是否不存在,如果为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)

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

试试这个...对我有用.. !! 并且您确定已将数据库文件放入资产文件夹中。

 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();      

}

当文件不存在无法创建时, FileOutputStream引发此异常。 我之前有这个探针,并设法通过在OutputStream mOutputStream = new FileOutputStream(f);之前先调用Context对象(或SQLiteDatabase类)的openOrCreateDatabase方法来解决它OutputStream mOutputStream = new FileOutputStream(f);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM