为什么不从文本文件中读取所有行? [英] Why not read all lines from text file?

查看:99
本文介绍了为什么不从文本文件中读取所有行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin项目的文件夹src/resources/中,我有文件pairs_ids.txt.

In my Kotlin project in folder src/resources/ I has file pairs_ids.txt.

这是一个属性文件:

key=value

所有行的数量为 1389 .

这里的代码逐行读取该文件的内容.

Here code that read content of this file line by line.

open class AppStarter : Application<AppConfig>() {
    override fun getName() = "stats"

    override fun run(configuration: AppConfig?, environment: Environment?) {
        val logger = LoggerFactory.getLogger(this::class.java)

        val inputStream = javaClass.getResourceAsStream("/pairs_ids.txt")
        val isr = InputStreamReader(inputStream)
        val br = BufferedReader(isr)
        for (line in br.lines()) {
            logger.info("current_line = " + line)
        }
        br.close()
        isr.close()
        inputStream.close()
    }
}

fun main(args: Array<String>) {
    AppStarter().run(*args)
}

问题在于 current_line 的计数每次都不同.

The problem is that count of current_line is every time different.

开始项目- current_line 的数量为 803 .

重新开始项目- current_line 的数量为 1140 .

Start again project - the count of current_line is 1140.

为什么每次计数都不相同且不等于 1389 ?

Why every time the count is different and not equal to 1389?

推荐答案

给出InputStream,您可以使用

Given an InputStream, you can use forEachLine to read each line separately:

inputStream.bufferedReader().use {
    it.forEachLine {
        println(it)
    }
}

注意:您应该使用 use ,这是一种确保读取完成后就关闭流的便捷方法(如user8159708所建议的那样).

Note: You should use use which is a convenient way to make sure the stream is closed once the reading is done (as user8159708 already suggested).

这篇关于为什么不从文本文件中读取所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆