如何导出room数据库并将其上载到firebase存储(然后下载并导入)?

2sbarzqh  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(291)

我想添加一个函数来导出数据库文件并将其上载到firebase存储,然后单击,下载数据库文件并将其替换(或导入)到当前数据库?idk我的方式是最好的或不是,但这是一个代码,我正在努力工作,这是一个代码,试图将数据库保存到sd卡(外部存储)。我不需要使用写外部存储,也不需要在本地存储上保存。直接使用firebase存储。另外,我还没有测试这段代码,因为我的手机是安卓11,外部存储无法使用。所以也许代码根本不起作用,idk。

private fun importDB() {
        try {

            val sd = Environment.getExternalStorageDirectory()
            val data = Environment.getDataDirectory()
            if (sd.canWrite()) {
                val currentDBPath = ("//data//" + "PackageName"
                        + "//databases//" + "DatabaseName")
                val backupDBPath = "/BackupFolder/DatabaseName"
                val backupDB = File(data, currentDBPath)
                val currentDB = File(sd, backupDBPath)
                val src = FileInputStream(currentDB).channel
                val dst = FileOutputStream(backupDB).channel
                dst.transferFrom(src, 0, src.size())
                src.close()
                dst.close()
                Toast.makeText(
                    baseContext, backupDB.toString(),
                    Toast.LENGTH_LONG
                ).show()
            }
        } catch (e: Exception) {
            Toast.makeText(baseContext, e.toString(), Toast.LENGTH_LONG)
                .show()
        }
    }

    //exporting database
    private fun exportDB() {
        val storageRef = FirebaseStorage.getInstance().reference
            .child("database/${FirebaseAuth.getInstance().currentUser?.uid}")
        try {
            val sd = Environment.getExternalStorageDirectory()
            val data = Environment.getDataDirectory()
            if (sd.canWrite()) {
                val currentDBPath = ("//data//" + "PackageName"
                        + "//databases//" + "DatabaseName")
                val backupDBPath = "/BackupFolder/DatabaseName"
                val currentDB = File(data, currentDBPath)
                val backupDB = File(sd, backupDBPath)
                val src = FileInputStream(currentDB).channel
                val dst = FileOutputStream(backupDB).channel
                dst.transferFrom(src, 0, src.size())
                src.close()
                dst.close()
                Toast.makeText(
                    baseContext, backupDB.toString(),
                    Toast.LENGTH_LONG
                ).show()
            }
        } catch (e: Exception) {
            Toast.makeText(baseContext, e.toString(), Toast.LENGTH_LONG)
                .show()
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题