从Scala中的config读取值 [英] Read values from config in Scala

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

问题描述

在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 getLineson 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屋!

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