【问题标题】:Kotlin - How to read from file asynchronously?Kotlin - 如何异步读取文件?
【发布时间】:2018-11-01 06:49:57
【问题描述】:

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

【问题讨论】:

    标签: kotlin kotlinx.coroutines


    【解决方案1】:

    查看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)
                }
            })
        }
    

    非常基础,不知道为什么它不是 coroutine-core lib 的一部分。

    【讨论】:

      【解决方案2】:

      以下是使用协程的方法:

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

      【讨论】:

      • 抱歉,您的示例根本不是异步的。您只需在另一个线程中使用阻塞 IO,调度程序线程将被阻塞,直到文件被读取。
      • 是的,这是众所周知的事实。但是,对于大多数用途(例如,GUI 编程)来说,它已经足够好了。我邀请您写一个答案,展示如何在 Kotlin/JVM 上进行真正的异步文件 IO。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2021-08-07
      • 2019-01-13
      • 2012-12-07
      相关资源
      最近更新 更多