我正在开发一个必须备份和还原数据库的应用程序。我已经编写了用于备份的代码,并且可以正常工作,但是我想在我的应用程序中还原备份数据库并删除那里已经存在的数据库。请提供针对非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();
}
}