简体   繁体   English

从SD卡/ Android外部存储还原Realm DB

[英]Restore Realm DB from SD Card/External Storage Android

I have a situation where i prompt user whether to backup their messages or no with the google backup service. 我遇到一种情况,我会提示用户是否使用Google备份服务备份他们的邮件还是不备份。 I am successfully backing up the current realm database onto the SD card from where the backup to google service will happen. 我已成功将当前领域数据库备份到SD卡上,将从那里进行Google服务备份。 But yet i though about the scenario where i want to actually restore the database from SD card to the current Realm Instance,meaning replace the current realm file with the one which is available on the SD Card. 但是,尽管如此,我还是想将数据库从SD卡实际还原到当前的Realm Instance,这意味着用SD卡上可用的文件替换当前的Realm文件。

In the older versions i saw that Realm gave a way to specify a custom path from which realm would read the database file,but in this new one i see none of it. 在较旧的版本中,我看到Realm提供了一种指定自定义路径的方式,Realm从该路径中读取数据库文件,但是在这个新版本中,我什么都看不到。

Any help please? 有什么帮助吗?

CREATE BACKUP FILE 创建备份文件

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();
}

RESTORE 恢复

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;
}

Hope this help. 希望能有所帮助。

Credit to link 归功于链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM