当前,我正在使用流在我的应用程序中实现SQlite db备份功能。 当我备份数据库时,它可以正常工作,并且文件中的数据已经通过“ SQlite的Db浏览器”进行了验证。但是,当尝试通过FilOuputStream从我的应用程序的数据库路径还原,并通过android SAF(存储访问框架)从返回的UrI还原到InputStream时,指向我放置了数据库备份的外部存储,我得到了损坏的数据库文件并且连接也关闭了。
以下是我为此目的使用的两种方法
进行备份
//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;
}
}
日志
我不明白为什么这样做,因为当我调试并将断点放入其有效的还原方法中时,这很奇怪,请帮忙找出那里出了什么问题。
答案 0 :(得分:0)
循环丢失了一些字节,所以我像
那样使用 filechannel
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;
}
}