我编写了一个函数来将整个文件分块并将其保存到一个列表位中,我得到了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的替代方法?
1条答案
按热度按时间qeeaahzv1#
readBytes
将此流完全读取到字节数组中。如果要避免内存不足,则需要将其作为流处理-因此使用read()
和available()
方法逐个读取字节,或者使用readNBytes(int len)
按注解中的建议分块读取