在我的 Kotlin 项目文件夹中 资源我有属性文件。如何从这个文件读取内容数据到 Properties 对象?
我试试这个:
val fis = FileInputStream("resources/pairs_ids.txt")
prop.load(fis);
logger.info("ETH_BTC_id = " + prop.get("ETH_BTC"))
但我得到错误:
Exception in thread "main" java.io.FileNotFoundException: resources\pairs_ids.txt (The system cannot find the path specified)
最佳答案
在这种情况下,我喜欢做的是:
@Suppress("UNCHECKED_CAST")
fun <T> getProp(key: String): T {
val props = javaClass.classLoader.getResourceAsStream("pairs_ids.txt").use {
Properties().apply { load(it) }
}
return (props.getProperty(key) as T) ?: throw RuntimeException("could not find property $key")
}
它将读取属性并尝试转换某个属性。
由于 kotlins 类型推断,它可以像这样使用:
val foo: String = getProp("ETH_BTC")
或这个:
val foo = getProp<String>("ETH_BTC")
关于kotlin - 如何将内容数据从属性文件读取到 Properties 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335825/