【问题标题】:Restore Realm DB from SD Card/External Storage Android从 SD 卡/外部存储 Android 恢复 Realm DB
【发布时间】:2017-02-17 08:15:21
【问题描述】:

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

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

有什么帮助吗?

【问题讨论】:

    标签: android database copy realm restore


    【解决方案1】:

    创建备份文件

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 2016-03-19
      • 2015-08-30
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 2015-07-31
      相关资源
      最近更新 更多