You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何恢复已备份的数据库?

Android 备份数据库恢复实现方案

前置准备

  • 将备份的.db文件传输到新设备的可访问目录(比如应用的外部存储目录context.getExternalFilesDir(null),或通过文件选择器选取)
  • 确保应用拥有对应存储权限:
    • Android 9及以下:申请READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限
    • Android 10及以上:使用Scoped Storage(通过文件选择器读取文件)或申请MANAGE_EXTERNAL_STORAGE权限(仅适用于特定场景)
  • 恢复前必须关闭当前应用的数据库连接,避免文件被占用(比如关闭数据库单例实例)

核心恢复代码实现

以下代码逻辑与你备份时的文件操作对应,实现将备份文件复制回应用的数据库目录:

public boolean restoreDatabase(Context context, String backupFilePath) {
    // 应用数据库目录路径,与备份时的源路径一致
    File dbDirectory = new File(context.getFilesDir().getParentFile().getPath() + "/databases");
    if (!dbDirectory.exists()) {
        dbDirectory.mkdirs();
    }

    File backupFile = new File(backupFilePath);
    if (!backupFile.exists()) {
        return false;
    }

    // 从备份文件名中提取原数据库名称(去掉时间戳后缀)
    String backupFileName = backupFile.getName();
    String originalDbName = backupFileName.substring(0, backupFileName.lastIndexOf("-"));
    if (!originalDbName.endsWith(".db")) {
        originalDbName += ".db";
    }

    File targetDbFile = new File(dbDirectory, originalDbName);

    // 关闭现有数据库连接(示例:替换为你的数据库关闭逻辑)
    // MyDbHelper.getInstance(context).close();

    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    boolean restoreSuccess = false;

    try {
        inputChannel = new FileInputStream(backupFile).getChannel();
        outputChannel = new FileOutputStream(targetDbFile).getChannel();
        // 复制备份文件到目标数据库路径
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        restoreSuccess = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭文件通道
        try {
            if (inputChannel != null) inputChannel.close();
            if (outputChannel != null) outputChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return restoreSuccess;
}

关键注意事项

  • 文件名处理:备份文件名格式为原数据库名-时间戳.db,恢复时需提取原数据库名,确保复制到正确的目标文件
  • Android 10+适配:若使用Scoped Storage,需通过ACTION_OPEN_DOCUMENT启动文件选择器获取备份文件的Uri,再通过ContentResolver打开输入流进行复制,避免直接操作文件路径
  • 恢复后重启:数据库恢复完成后,需重启应用才能让系统加载新的数据库文件
  • 异常处理:实际使用中需补充更完善的异常捕获逻辑,比如文件读写失败、权限不足等情况的提示

内容的提问来源于stack exchange,提问作者Bernd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:17:14