从 SD Card/External 存储 Android 恢复领域数据库

Restore Realm DB from SD Card/External Storage Android

我有一种情况,我提示用户是否使用 google 备份服务备份他们的消息。我成功地将当前领域数据库备份到 SD 卡上,从那里备份到 google 服务。 但是我还是想到了我想将数据库从 SD 卡实际恢复到当前领域实例的场景,这意味着用 SD 卡上可用的领域文件替换当前领域文件。

在旧版本中,我看到 Realm 提供了一种方法来指定自定义路径,领域将从中读取数据库文件,但在这个新版本中,我看到了 none。

有什么帮助吗?

创建备份文件

public void backup() {
    try {
        // create a backup file
        File exportRealmFile;
        exportRealmFile = new File(EXPORT_REALM_PATH, EXPORT_REALM_FILE_NAME);

        // if backup file already exists, delete it
        exportRealmFile.delete();

        // copy current realm to backup file
        realm.writeCopyTo(exportRealmFile);

    } catch (IOException e) {
        e.printStackTrace();
    }
    realm.close();
}

恢复

private String copyBundledRealmFile(String oldFilePath, String outFileName) {
    try {
        File file = new File(activity.getApplicationContext().getFilesDir(), outFileName);

        FileOutputStream outputStream = new FileOutputStream(file);

        FileInputStream inputStream = new FileInputStream(new File(oldFilePath));

        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, bytesRead);
        }
        outputStream.close();
        return file.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

希望对您有所帮助。

归功于 link