很久以前,我已经在我的应用程序中实现了简单的备份/还原解决方案。创建备份时,原理很简单,将内部数据库复制到外部存储,从备份还原时-将外部数据库文件复制到内部数据库。
但是当我尝试从另一个应用程序(显然不包含我的应用程序所需的表)从备份文件还原时,问题就来了。如何验证somefile.db
或somefile.sqlite
实际上是我的应用程序的备份?它确实包含所需的架构。因为如果我从random file.db中恢复,我的应用程序崩溃,并提示消息数据库不包含所需的表
fun restoreDbFromUri(uri: Uri): Boolean {
try {
val cr = context.contentResolver
cr.openFileDescriptor(uri, "r")
?.use { pfd ->
FileInputStream(pfd.fileDescriptor)
.use { fis -> // TODO before coping, I need verify that this file is actually correct database, with all needed tables
dbOpenHelper.close()
internalDbFile.transferFrom(fis)
return true
}
}
} catch (e: Exception) {
presenter.toastPresenter.onShowErrorToast(e.localizedMessage)
e.printStackTrace()
}
presenter.toastPresenter.onShowErrorToast()
return false
}
val internalDbFile: File
get() = context.getDatabasePath("prana_breath.sqlite")
@Throws(IOException::class)
fun File.transferFrom(srcInput: FileInputStream) {
FileOutputStream(this).use { dstOut ->
dstOut.channel.use { dstChannel ->
srcInput.channel.use { srcChannel ->
dstChannel.transferFrom(srcChannel)
}
}
}
}
@Throws(IOException::class)
fun FileChannel.transferFrom(srcChannel: FileChannel) {
this.transferFrom(srcChannel, 0, srcChannel.size())
}
您首先可以打开文件并检查标题的前16个字节,它必须为“ SQLite格式3 \ 000”。
例如:-
const val SQLITEFILEHEADER = "SQLite format 3\u0000"
private fun isFileSQLiteDatabase(f: File): Boolean {
val fis: InputStream
if (!f.isFile) return false
val header = ByteArray(16)
try {
fis = FileInputStream(f)
fis.read(header)
if (String(header) != SQLITEFILEHEADER) {
fis.close()
return false
}
} catch (e: IOException) {
return false
}
return true
}
这将消除几乎所有非db文件。然后,要检查数据库是否具有预期的表(和/或其他实体),可以使用SQliteDatabase的openDatabase方法之一将文件作为SQLiteDatabase打开,然后查询sqlite_master表以检查预期的表(和/或其他实体)按预期的方式存在,确保您关闭数据库。
所以您可能会有类似:-]的东西>
private fun isDBValid(f: File, entityList: Array<String>): Boolean {
var matchcount = 0
if (!isFileSQLiteDatabase(f)) return false
try {
val db = SQLiteDatabase.openDatabase(f.path, null, SQLiteDatabase.OPEN_READWRITE)
val csr = db.query("sqlite_master", null, null, null, null, null, null)
while (csr.moveToNext()) {
for (s in entityList) {
if (s.toLowerCase() == csr.getString(csr.getColumnIndex("name")).toLowerCase()) {
matchcount++
break
}
}
}
csr.close()
db.close()
} catch (e: SQLiteException) {
return false;
}
return matchcount != entityList.size
}
然后您可以使用:-
fun restore DbFromUri(uri: Uri): Boolean {
//<<<<< DB VERIFICATION >>>>>
if (isDBValid(File(uri.path), requiredEntities)) {
} else {
return false
}
try {
val cr = context.contentResolver
cr.openFileDescriptor(uri, "r")
?.use { pfd ->
FileInputStream(pfd.fileDescriptor)
.use { fis -> // TODO before coping, I need verify that this file is actually correct database, with all needed tables !!!!DONE ABOVE!!!!
dbOpenHelper.close()
internalDbFile.transferFrom(fis)
return true
}
}
} catch (e: Exception) {
presenter.toastPresenter.onShowErrorToast(e.localizedMessage)
e.printStackTrace()
}
presenter.toastPresenter.onShowErrorToast()
return false
}