我正在使用 Google Drive API 来备份我的 Android 应用程序数据,类似于 Whatsapp。我将多个文件(例如 db 和其他杂项)中的数据写入单个二进制文件并将其上传到驱动器。但是,当我下载相同的文件来恢复数据时,下载文件末尾的字节与上传的字节不同。知道为什么会这样吗?
我的代码
备份
backupFile.outputStream().use { outputStream ->
// Write File 1 data
file1.inputStream().use {
val data = it.readBytes()
outputStream.write(data.size)
outputStream.write(data)
}
// Write File 2 data
file2.inputStream().use {
val data = it.readBytes()
outputStream.write(data.size))
outputStream.write(data)
}
// Write File 3 data
file3.inputStream().use {
val shmData = it.readBytes()
outputStream.write(shmData.size.toByteArray())
outputStream.write(shmData)
}
}
恢复
dataInputStream.use { inputStream ->
// Read File 1 Data
file1.outputStream().use {
val size = inputStream.read()
val data = ByteArray(size)
inputStream.read(data)
it.write(data)
}
// Read File 2 Data
dbWalFile.outputStream().use {
val size = inputStream.read()
val data = ByteArray(size)
inputStream.read(data)
it.write(data)
}
// Read File 3 Data
dbShmFile.outputStream().use {
val size = inputStream.read()
val data = ByteArray(size)
inputStream.read(data)
it.write(data)
}
}
当我尝试这种方式时,我在最后一次
read()
调用 File 3 中获得的大小值返回一些大得离谱的值,这会导致 OutOfMemoryError
异常。
我的驱动器代码
上传
suspend fun uploadBackupFile(file: File) = withContext(Dispatchers.IO) {
val gFile = com.google.api.services.drive.model.File().apply {
name = file.name
parents = backupParents // String With Drive Spaces
}
val fileContent = FileContent(BACKUP_MIME_TYPE, file) // MIME TYPE is application/octet-stream
val createdFile = getDriveService().Files().create(gFile, fileContent).execute()
下载
suspend fun downloadBackupFile(fileId: String): InputStream = withContext(Dispatchers.IO) {
getDriveService()
.Files()
.get(fileId)
.executeMediaAsInputStream()
}
从
InputStream
返回的downloadBackupFile()
就是我恢复时读取的数据
您正在编写一个字节数组,其大小为:
outputStream.write(shmData.size.toByteArray())
然后只读回一个字节:
val size = inputStream.read()