有没有一种方法,无需解析为传统的类 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/