为什么Kotlin的(for)循环无法在org.slf4j.Logger中正常工作? [英] Why Kotlin's loop (for) not work correct with org.slf4j.Logger?

查看:281
本文介绍了为什么Kotlin的(for)循环无法在org.slf4j.Logger中正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此处代码: 这是一个属性文件:

Here code: This is a property file:

key=value

所有行的数量为 1389 .

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

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

import org.slf4j.LoggerFactory
private val logger = LoggerFactory.getLogger("Exchange")

 private var allSymbolsIDsMap: Map<String, String> = mapOf()    
 val pairsIDs = getResourceAsText("/pairs_ids.txt")
 allSymbolsIDsMap = pairsIDs.split(",").associate {
 val (left, right) = it.split("=")
          left to right.toString()
 }
 logger.info("allSymbolsIDsMap_size = " + allSymbolsIDsMap.size)
 var countAllSymbolHandler = 0
 for ((key, value) in allSymbolsIDsMap) {
   countAllSymbolHandler++
   logger.info("countAllSymbolHandler = $countAllSymbolHandler")
}

private fun getResourceAsText(path: String): String {
    return object {}.javaClass.getResourceAsStream(path).bufferedReader().use { it.readText() }
}

结果:

开始项目:

allSymbolsIDsMap_size = 1389
Start project - "countAllSymbolHandler =" print 1113 times

再次启动项目:

allSymbolsIDsMap_size = 1389
"countAllSymbolHandler =" print 242 times

如果将logger.info替换为简单的println,则说明成功.计数始终为 1389 .

If replace logger.info by simple println then success work. The count is always 1389.

为什么循环(for)无法与 logger 一起正常工作?

Why loop (for) not work correct with logger?

推荐答案

尝试:

override fun run(configuration: AppConfig?, environment: Environment?) {
        val logger = LoggerFactory.getLogger(this::class.java)
        javaClass.getResourceAsStream("/pairs_ids.txt").bufferedReader().use { reader -> reader.readLines() }.forEach { line -> logger.info(line) }
    }

在使用输入/输出流时,请使用Kotlin的use扩展方法,并在use块内进行所有处理.

When playing with input/output streams, use Kotlin's use extension methods, and do all of your processing inside of the use block.

这将处理所有打开和关闭流的操作,这样就不会有泄漏,或者忘记关闭/冲洗等.

This will handle all opening and closing of the streams so that there are no leaks, or forgetting to close/flush etc.

这篇关于为什么Kotlin的(for)循环无法在org.slf4j.Logger中正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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