为此,我找不到合适的解决方案。甚至我都不知道如何在房间数据库中备份和还原备份文件。请帮我怎么做。
我没有任何疑问,但是堆栈溢出给我错误,这就是为什么我写这行代码的原因
我找到了备份的方法,但找不到还原数据库的解决方案 当我检查应用程序是否显示还原成功,但应用程序中不存在真实数据时
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();
}
}
}
}
答案 0 :(得分:1)
这是使用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();
}
请参见以下链接,以将onOpen()
回调放在Room中的位置:
https://medium.com/@srinuraop/database-create-and-open-callbacks-in-room-7ca98c3286ab