Kotlin-如何异步读取文件?

ali*_*ari 2 kotlin kotlinx.coroutines

有没有kotlin惯用的方式来异步读取文件内容?我在文档中找不到任何内容。

Mar*_*nik 6

以下是使用协程进行操作的方法:

launch {
    val contents = withContext(Dispatchers.IO) {
        FileInputStream("filename.txt").use { it.readBytes() }
    }
    processContents(contents)
}
go_on_with_other_stuff_while_file_is_loading()
Run Code Online (Sandbox Code Playgroud)


Jam*_*Lan 6

Java NIO 异步通道就是您想要的工具。从协程示例中查看此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)
            }
        })
    }
Run Code Online (Sandbox Code Playgroud)

你只需打开一个然后在协程中AsynchronousFileChannel调用它,aRead()

val channel = AsynchronousFileChannel.open(Paths.get(fileName))
try {
    val buf = ByteBuffer.allocate(4096)
    val bytesRead = channel.aRead(buf)
} finally {
    channel.close()
}
Run Code Online (Sandbox Code Playgroud)

这是一个必不可少的功能,不知道为什么它不是 coroutine-core lib 的一部分。