首页 > 解决方案 > 以编程方式导入 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)
}

标签: androidsqliteandroid-sqliteandroid-room

解决方案


您的代码的一个问题是它反复覆盖输出文件中的同一位置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
}

推荐阅读