从文件加载数据库

Room loading database from file

如何从 SD 卡上的文件加载 Room Android 数据库?这是保存数据库的代码:

private void saveAppDatabase() {
    try {
        File sd = Environment.getExternalStorageDirectory();

        if (sd.canWrite()) {
            String currentDBPath =
                    getDatabasePath("AppDatabase").getAbsolutePath();
            String backupDBPath = "AppDatabase.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

感谢您的帮助!

要么将数据库复制回您复制它的位置,要么尝试将完全限定路径传递给 Room.databaseBuilder() 并查看是否可行。如果现有的不起作用,您可能需要创建自己的 SupportSQLiteOpenHelper.Factory。我不建议使用外部存储上的数据库,因为如果其他应用程序在您使用该文件时试图弄乱它,就会发生不好的事情。 – CommonsWare