首页 > 解决方案 > 使用动态文件名获取 SQLite 数据库备份

问题描述

如果有多个.db文件,如何获取最新的 SQLite 数据库(在下面的屏幕截图中,我要获取 11408102018000005)已备份到 SD 卡上?

笔记:

文件类型是动态的。所以图像上的最后一个数字是递增的。

这是图像: 在此处输入图像描述

这是我在恢复 SQLite 数据库时的代码。

private void restoreDB() {
    try {
        File[] sd = getContext().getExternalFilesDirs(null);

        if (sd[1].canWrite()) {
            File backupDB = new File(sd[1] + "/" + curControlNo);    //<--- what to put here. This is just a test path and name
            File currentDB = new File(getContext().getDatabasePath(DBHelper.DB_NAME).getPath());

            FileChannel src = new FileInputStream(backupDB).getChannel();
            FileChannel dst = new FileOutputStream(currentDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getContext(), "Import Successful!", Toast.LENGTH_SHORT).show();
            openHome();
        }
    } catch (Throwable e) {
        Toast.makeText(getContext(), "Import Failed!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

标签: androidsqlite

解决方案


您需要创建文件并传递要保存的数据库名称,如下所示:

File backupDB = new File(sd[1], DBHelper.DB_NAME); 

希望它会奏效。


推荐阅读