将db从资产复制到设备数据文件夹时出现FileNotFoundException

Mic*_*ele 1 sqlite android assets filenotfoundexception fileoutputstream

我试过很多方法将我的sqlite db文件复制到我的/ data/data/packagename/databases文件夹,但是我仍然陷入FileNotFoundException,由FileOutputStream对象触发...这是代码:

public static boolean checkCopyDb(Context c, DbHandler _db) {
    try {
        String destPath = "/data/data/" + c.getPackageName() + "/databases/db_sociallibraries.db";

        File dbFile = new File(destPath);

        if(!dbFile.exists()) {
            _db.copyDb(c.getAssets().open(DB_NAME), new FileOutputStream(destPath)); // Line 44 - Throws the exception
        }
        return true;
    }
    catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

private void copyDb(InputStream inputStream, OutputStream outputStream) throws IOException {

    byte[] buffer = new byte[1024];
    int length;

    while((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
    }

    inputStream.close();
    outputStream.close();
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:java.io.FileNotFoundException:/data/data/com.test.michelemadeddu.sociallibraries/databases/db_sociallibraries.db:打开失败:ENOENT(没有这样的文件或目录)02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:at libcore.io.IoBridge.open(IoBridge.java:409 )02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:at java.io.FileOutputStream.(FileOutputStream.java:88)02-09 01:28:46.384 24222- 24222/com.test.michelemadeddu.sociallibraries W/System.err:at java.io.FileOutputStream.(FileOutputStream.java:128)02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:at java.io.FileOutputStream.(FileOutputStream.java:117)02-09 01:28:46.384 24222-24222/com.test.michelemadeddu.sociallibraries W/System.err:at com.test.michelemadeddu. sociallibraries.DbHandler.checkCopyDb(DbHandler.java:44)

难道我做错了什么?谢谢

job*_*azy 8

为了兼容性,您可以将内部数据库路径更改为以下内容

if(android.os.Build.VERSION.SDK_INT >= 17) {
   DB_PATH = context.getApplicationInfo().dataDir + "/databases/";         
} else {
   DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
Run Code Online (Sandbox Code Playgroud)