从Scala中的config读取值

Ste*_*sky 11 scala file

在Scala中,如果我有以下配置:

id = 777
username = stephan
password = DG#%T@RH
Run Code Online (Sandbox Code Playgroud)

我们的想法是打开一个文件,将其转换为字符串,getLines然后根据左侧键获取右侧值.将常量配置值读入我的应用程序的最佳代码是什么?

客户用法: val username = config.get("username")

End*_*Neu 24

最好的方法是使用一个.conf文件,ConfigFactory而不是自己做所有的文件解析:

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")
Run Code Online (Sandbox Code Playgroud)

我通常使用scalaz Validation进行parseFile操作,以防文件不存在,但try/catch如果你不知道如何使用它,你可以简单地使用.