Read values from config in Scala

前端 未结 3 1022
轻奢々
轻奢々 2020-12-31 07:26

In Scala, if I have the following config:

id = 777
username = stephan
password = DG#%T@RH

The idea is to open a file, transform it into a s

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 07:55

    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")
    

    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.

提交回复
热议问题