Kotlin - 如何异步读取文件?
Kotlin - How to read from file asynchronously?
是否有任何 kotlin 惯用的方式来异步读取文件内容?我在文档中找不到任何内容。
以下是使用协程的方法:
launch {
val contents = withContext(Dispatchers.IO) {
FileInputStream("filename.txt").use { it.readBytes() }
}
processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
从 coroutine example 中查看这个 AsynchronousFileChannel.aRead
扩展函数:
suspend fun AsynchronousFileChannel.aRead(buf: ByteBuffer): Int =
suspendCoroutine { cont ->
read(buf, 0L, Unit, object : CompletionHandler<Int, Unit> {
override fun completed(bytesRead: Int, attachment: Unit) {
cont.resume(bytesRead)
}
override fun failed(exception: Throwable, attachment: Unit) {
cont.resumeWithException(exception)
}
})
}
它非常基础,不知道为什么它不是协程核心库的一部分。
是否有任何 kotlin 惯用的方式来异步读取文件内容?我在文档中找不到任何内容。
以下是使用协程的方法:
launch {
val contents = withContext(Dispatchers.IO) {
FileInputStream("filename.txt").use { it.readBytes() }
}
processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
从 coroutine example 中查看这个 AsynchronousFileChannel.aRead
扩展函数:
suspend fun AsynchronousFileChannel.aRead(buf: ByteBuffer): Int =
suspendCoroutine { cont ->
read(buf, 0L, Unit, object : CompletionHandler<Int, Unit> {
override fun completed(bytesRead: Int, attachment: Unit) {
cont.resume(bytesRead)
}
override fun failed(exception: Throwable, attachment: Unit) {
cont.resumeWithException(exception)
}
})
}
它非常基础,不知道为什么它不是协程核心库的一部分。