[英]how to restore backup file in room database easily?
我找不到一个好的解决方案。 即使我对在 Room 数据库中备份和恢复备份文件一无所知。 请帮我怎么做。
I Don"t Have Any Longer Question But Stack OverFlow Giving me Error 这就是我写这行的原因
我找到了采取备份的方法但是当我检查应用程序显示还原成功但在应用程序中不可用的实际数据时,我找不到还原数据库的解决方案
public static boolean backUpDatabase(Context context) throws IOException {
db.close();
File dbFile = new File(String.valueOf(context.getDatabasePath(MainDatabase.DATABASE_NAME)));
File sDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Tuition App2");
String fileName = "TuitionApp_BackUp.db";
String sfPath = sDir.getAbsolutePath()+"/"+fileName;
if (!sDir.exists()){
sDir.mkdirs();
}
File saveFile = new File(sfPath);
if (saveFile.exists()){
saveFile.delete();
}
if (saveFile.createNewFile()){
int bufferSize = 8 * 1024;
byte[] buffer = new byte[bufferSize];
int bytes_read = bufferSize;
OutputStream saveDb = new FileOutputStream(sfPath);
InputStream inDb = new FileInputStream(dbFile);
while ((bytes_read = inDb.read(buffer, 0, bufferSize)) > 0) {
saveDb.write(buffer, 0, bytes_read);
}
saveDb.flush();
inDb.close();
saveDb.close();
//saving path in to sharedPraf sm is object of that class
sm.saveBackFileName(context,sfPath);
return true;
}
return false;
}
public static boolean restoreDataBase(Context context) throws FileNotFoundException {
db.close();
File sDir = new File(sm.getBackupFileName(context));
File finalFile = new File(sDir.getAbsolutePath());
InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(finalFile));
File oldDb = context.getDatabasePath(MainDatabase.DATABASE_NAME);
if ( inputStream!= null){
try {
copyFile((FileInputStream) inputStream,new FileOutputStream(oldDb));
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
这是 SQLite,但过程应该是相同的:
接下来还将向您展示如何遵守范围存储,因为您现在的做法在 Android 11 上根本无法使用:
https://developer.android.com/preview/privacy/storage
您可能还想在onOpen()
禁用预写日志。 这是它在 SQLite 中的样子:
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
//disable write-ahead logging to make backup/restore work on all devices.
db.disableWriteAheadLogging();
}
请参阅此链接以了解在 Room 中放置onOpen()
回调的位置:
https://medium.com/@srinuraop/database-create-and-open-callbacks-in-room-7ca98c3286ab
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.