android - 以编程方式导入 Room 数据库
问题描述
为了将房间数据库导出为备份文件,我正在调用方法RoomDatabase.close()
,因为当您关闭数据库时,它会将所有 db 文件合并.db-wal
到.db-shm
一个MyApp.db
文件中,我使用此代码将 MyApp.db 文件导出到外部存储:
try {
val dbFile = File(databasePath)
val fileInputStream = FileInputStream(dbFile)
val buffer = ByteArray(1024)
while (true) {
val length = fileInputStream.read(buffer)
if (length <= 0)
break
outputStream?.write(buffer, 0, length)
}
} catch (e: IOException) {
Log.e(TAG, "EXCEPTION WHILE WRITING DATABASE TO BACKUP", e)
}
这种和平的代码正确执行并导出数据库,然后我使用下面的代码导入数据库它需要导出的MyApp.db
文件并替换当前使用的数据库,但是在应用程序中即使我重新打开应用程序它也会显示空数据库,我猜是因为当我'正在导入数据库,它只导入这个 db 文件 MyApp.db,但它丢失了.db-wal
,.db-shm
如何从 .db 中提取这些文件?我做对了吗?
try {
val parcelFileDescription = contents.parcelFileDescriptor
val fileInputStream = FileInputStream(parcelFileDescription.fileDescriptor)
val output = FileOutputStream(dbPath)
val buffer = ByteArray(1024)
while (true) {
val length = fileInputStream.read(buffer)
if (length <= 0)
break
output.write(buffer, 0, length)
}
output.flush()
output.close()
fileInputStream.close()
Toast.makeText(context, "Import completed", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Log.e("TAGAS", "EXCEPTION: ", e)
}
解决方案
您的代码的一个问题是它反复覆盖输出文件中的同一位置output.write(buffer, 0, length)
。将 0 替换为索引变量:
var index = 0
while (true) {
val length = fileInputStream.read(buffer)
if (length <= 0)
break
output.write(buffer, index, length)
index += length
}
推荐阅读
- python - 查找与字典键关联的值的数量并绘制 distplot
- android - 我将如何从我的微调器中检索用户选择的位置?
- c# - 访问 Windows 服务帐户用户名/密码
- r - 使用 pivot_wider 从在多列中具有变量的杂乱数据创建新变量
- apache-kafka-streams - 使用 Spring-Kafka 和 Confluent Registry 的外键连接示例配置
- bash - 如何在一行中运行 bash 脚本和输入
- c# - Roslyn - How to got line by line through a method?
- javascript - 使用 bitbucket 管道在 Firebase 托管中部署 Angular 应用程序的问题
- laravel - 将数据从 API 保存到数据库 Laravel
- python-3.x - 如何通过 OAuth 通过 CData ODBC 驱动程序对 Salesforce 进行身份验证?