I am new to Scala programming and I wanted to read a properties file in Scala.
I can't find any APIs to read a property file in Scala.
Please let me know if there are any API for this or other way to read properties files in Scala.
除了表单Java API之外,Typesafe还有一个名为config的库,它有一个很好的API,用于处理不同类型的配置文件。
You will have to do it in similar way you would with with Scala Map
to java.util.Map
. java.util.Properties
extends java.util.HashTable
whiche extends java.util.Dictionary
.
scala.collection.JavaConverters
has functions to convert to and fro from Dictionary
to Scala mutable.Map
:
val x = new Properties
//load from .properties file here.
import scala.collection.JavaConverters._
scala> x.asScala
res4: scala.collection.mutable.Map[String,String] = Map()
You can then use Map
above. To get and retrieve. But if you wish to convert it back to Properties
type (to store back etc), you might have to type cast it manually then.
您只需使用Java API即可 。
Consider something along the lines
def getPropertyX: Option[String] = Source.fromFile(fileName)
.getLines()
.find(_.startsWith("propertyX="))
.map(_.replace("propertyX=", ""))
Following the approach from Raul, you have to parse the line and get the value after the =, this works for me:
Source.fromFile(fileName)
.getLines()
.find(_.startsWith("version="))
.get
.split("=")(1)
The same thing, select the line and split it by =, you will get an Array[String], then choose the value after =, I mean the second element in the array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.