簡體   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