【问题标题】:Importing a Room database programmatically以编程方式导入 Room 数据库
【发布时间】:2018-11-27 12:03:23
【问题描述】:

为了将房间数据库导出为备份文件,我正在调用方法 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)
}

【问题讨论】:

    标签: android sqlite android-sqlite android-room


    【解决方案1】:

    您的代码的一个问题是它反复覆盖输出文件output.write(buffer, 0, length) 中的同一位置。将 0 替换为索引 var:

    var index = 0
    while (true) {
        val length = fileInputStream.read(buffer)
        if (length <= 0)
            break
        output.write(buffer, index, length)
        index += length
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 2010-11-14
      相关资源
      最近更新 更多