android Kotlin中未保存到存储的块文件出错

k5ifujac  于 2023-01-11  发布在  Android
关注(0)|答案(1)|浏览(166)

我编写了一个函数来将整个文件分块并将其保存到一个列表位中,我得到了memoryOutOf异常:

override suspend fun chunkFile(
        file: File,
        chunkSize: Int
    ): MutableList<ByteArray> {
        val chunks: MutableList<ByteArray> = arrayListOf()
        val sizeOfFiles: Int = 5242880
        val buffer = ByteArray(sizeOfFiles)
        val bufferedInputStream = BufferedInputStream(withContext(Dispatchers.IO) {
            FileInputStream(file)
        })
        var tmp = 0

        return withContext(Dispatchers.IO) {
            while (bufferedInputStream.read(buffer).also { tmp = it } > 0) {
                if (isActive) {
                    var out: ByteArrayInputStream? = null
                    var readByteArray: ByteArray? = null

                    out = ByteArrayInputStream(
                        buffer,
                        0,
                        tmp
                    )
                    readByteArray = out.readBytes()
                    readByteArray?.let {
                        chunks.add(it)
                    }
                    out.close()
                }
            }
            bufferedInputStream.close()
            chunks
        }
    }

readByteArray = out.readBytes()行中出现错误
有没有不影响内存的阅读ByteArray的替代方法?

qeeaahzv

qeeaahzv1#

readBytes将此流完全读取到字节数组中。如果要避免内存不足,则需要将其作为流处理-因此使用read()available()方法逐个读取字节,或者使用readNBytes(int len)按注解中的建议分块读取

相关问题