目前,我正在使用stream在我的应用程序中实现SQlite数据库备份功能。当我备份数据库时,它工作,文件有数据,因为我已经通过“SQlite数据库浏览器”进行了验证。但是,当尝试通过FilOuputStream从我的应用程序的数据库路径进行恢复,并从android SAF(存储访问框架)返回的UrI (存储访问框架)指向我放置数据库备份的外部存储时,我得到损坏的数据库文件,连接也关闭。
以下是我用于此目的的两种方法
进行备份
//back db to a URI
public synchronized static boolean backupDb(Context context, Uri uri, String dbNam) throws IOException {
File dbFile = new File(context.getDatabasePath(dbNam).getPath());
FileInputStream inFilStream = new FileInputStream(dbFile);
OutputStream outFilStream = context.getContentResolver().openOutputStream(uri);//new FileOutputStream(backupFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inFilStream.read(buffer)) > 0) {
outFilStream.write(buffer, 0, length);
}
outFilStream.flush();
outFilStream.close();
inFilStream.close();
return true;
}恢复备份
//restore db from a URI
public static synchronized boolean restoreBackup(Context context, Uri uri, String dbNam) {
try {
InputStream inFilStream = context.getContentResolver().openInputStream(uri);
File dbFile = new File(context.getDatabasePath(dbNam).getPath());
FileOutputStream outFilStream = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inFilStream.read(buffer)) > 0) {
outFilStream.write(buffer, 0, length);
Log.wtf("db", "restoring backup up");
}
outFilStream.flush();
// using outFilStream.getFD().sync(); also not working
outFilStream.close();
inFilStream.close();
return true;
} catch (IOException e) {
return false;
}
}日志

我不明白为什么它会这样做,因为当我调试它并在它工作的恢复方法中设置断点时,它是相当奇怪的,请任何人帮助找出哪里出了问题。
发布于 2020-11-30 22:00:50
循环丢失了一些字节,所以我使用了文件通道,如下所示
public synchronized static boolean saveDbBackup(Context context, Uri uri, String dbNam) throws IOException {
File dbFile = new File(context.getDatabasePath(dbNam).getPath());
FileChannel inFilChannel = new FileInputStream(dbFile).getChannel();
FileChannel outFilChannel = ((FileOutputStream)context.getContentResolver().openOutputStream(uri)).getChannel();//new FileOutputStream(backupFile);
outFilChannel.transferFrom(inFilChannel,0,inFilChannel.size());
outFilChannel.close();
inFilChannel.close();
return true;
}public static synchronized boolean restoreDbBackup(Context context, Uri uri, String dbNam) {
try {
FileChannel inFileChannel= ((FileInputStream) context.getContentResolver().openInputStream(uri)).getChannel();
FileChannel outFileChannel= new FileOutputStream(new File(context.getDatabasePath(dbNam).getPath())).getChannel();
outFileChannel.transferFrom(inFileChannel,0,inFileChannel.size());
outFilChannel.close();
inFilChannel.close();
return true;
} catch (IOException e) {
return false;
}
}https://stackoverflow.com/questions/55038870
复制相似问题