繁体   English   中英

备份和恢复数据库android studio

[英]Backup and Restore Database android studio

我想在我的应用程序中对数据库进行备份和恢复,以便当用户删除应用程序并重新安装时,他们可以恢复他们的数据。 在 Android Studio 中做到这一点的最佳方法是什么?

有多种类型可用于备份和还原到您的 db 文件,例如 Google 驱动器、保管箱和一个驱动器。 如果您想从本地存储进行备份,请尝试以下给定的代码。

备份代码:

  public void backUp() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//your package     name//databases//dbname.db";
            String backupDBPath = "dbname.db";

            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            Log.d("backupDB path", "" + backupDB.getAbsolutePath());

            if (currentDB.exists()) {
                FileChannel src = new     FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getApplicationContext(), "Backup is successful to SD card", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

恢复代码:

  public void restore() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//your package name//databases//dbname.db";;
            String backupDBPath = "dbname.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(backupDB).getChannel();
                FileChannel dst = new FileOutputStream(currentDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

暂无
暂无

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

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