Kotlin - 只读文件中的前 n 行

标签 kotlin

有没有一种方法,无需解析为传统的类 Java for 循环,就可以限制 BufferedReader 读取的行数?

以这段代码为例:

bufferedReader.useLines { it }
            .take(10)
            .toList()

useLines 的文档指出:

Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once * the processing is complete.

据我了解,这意味着将读取整个文件,然后才从序列中过滤掉前十个文件。除了仅获取第一行外,我在网上找不到任何解决此问题的方法。

最佳答案

Sequence 是一个延迟计算的集合。这意味着只会处理必要的项目,因此如果您take(10),只会处理前 10 行。

因此文档中的关键字是:

Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once the processing is complete.

现在 useLines 会在其 block 完成后立即关闭源代码,从而使您的代码不正确。相反,请使用以下内容:

val list : List<String> = bufferedReader
    .useLines { lines: Sequence<String> ->
        lines
            .take(10)
            .toList()
    }

关于Kotlin - 只读文件中的前 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795270/

相关文章:

android - 我如何从我的Android应用程序共享whatsapp语音笔记(.opus)文件?

closures - 从 forEachLine 返回

javafx - 如何在JavaFX的MenuButton中创建子菜单?

java - 了解 kotlin 执行器

java - 低功耗蓝牙扫描仪似乎工作正常,但找不到任何设备

kotlin - 哪种是Kotlin koan “Partition”的首选解决方案,为什么?

kotlin - 什么时候应该使用 let {} 以及什么时候应该使用普通 != null

android - 即使我在单选按钮上明确设置了选中状态,RecyclerView 中的单选按钮也会随机取消选中

kotlin - 是否有任何理由使用 suspend fun fn(...) : Either<Throwable, A> 而不是 suspend fun fn(...) : A?

android - 不受支持的元数据版本。检查您的 Kotlin 版本是否 >= 1.0 : java. lang.IllegalStateException