gpt4 book ai didi

java - 在android中使用新的SQLite数据库恢复和删除旧的SQLite数据库

转载 作者:行者123 更新时间:2023-12-01 17:18:55 26 4
gpt4 key购买 nike

我正在开发一个应用程序,我必须在其中备份和恢复我的数据库。我已经编写了备份代码并且它正在工作,但我想恢复我的应用程序中的备份数据库并删除那里已经存在的数据库。请提供未 root 的 Android 设备的解决方案。谢谢你!我的备份代码:

private void exportDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+getPackageName()+"/databases/"+DatabaseHelper.DATABASE_NAME;
String backupDBPath = "abcrecord.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}

最佳答案

您的代码显示您可以备份数据库。因此,为了恢复该数据库,我们切换源文件和目标文件,如下所示:

private void RestoreDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+getPackageName()+"/databases/"+DatabaseHelper.DATABASE_NAME;
String backupDBPath = "abcrecord.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(backupDB).getChannel();
destination = new FileOutputStream(currentDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB restored!", Toast.LENGTH_LONG).show();
backupDB.delete(); //for deleting the backup database after restoring
} catch(IOException e) {
e.printStackTrace();
}
}

关于java - 在android中使用新的SQLite数据库恢复和删除旧的SQLite数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61336779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com