从Scala中的config读取值 [英] Read values from config in Scala
问题描述
在Scala中,如果我具有以下配置:
In Scala, if I have the following config:
id = 777
username = stephan
password = DG#%T@RH
这个想法是打开一个文件,将其转换为字符串,对该文件执行getLines
,然后根据左侧键获取右侧值.将常量配置值读入我的应用程序的最好的代码是什么?
The idea is to open a file, transform it into a string, do getLines
on it and get the right-hand side value based on the left-hand side key. What would be the nicest code to read constant configuration values into my app?
客户端用法:val username = config.get("username")
推荐答案
最好的方法是使用.conf
文件和ConfigFactory
,而不必自己进行所有文件解析:
Best way would be to use a .conf
file and the ConfigFactory
instead of having to do all the file parsing by yourself:
import java.io.File
import com.typesafe.config.{ Config, ConfigFactory }
// this can be set into the JVM environment variables, you can easily find it on google
val configPath = System.getProperty("config.path")
val config = ConfigFactory.parseFile(new File(configPath + "myFile.conf"))
config.getString("username")
我通常将scalaz Validation
用于parseFile
操作,以防文件不存在,但是如果您不知道如何使用它,则可以简单地使用try/catch
.
I usually use scalaz Validation
for the parseFile
operation in case the file it's not there, but you can simply use a try/catch
if you don't know how to use that.
这篇关于从Scala中的config读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!