scala读取配置文件
Class:
package libparser
import scala.collection.mutable
import scala.util.matching.Regex
class conf {
def parser(value: String) = {
var cs = mutable.Map.empty[String, String]
val pattern = new Regex("""(^[a-zA-Z0-9_-]+?)\s+([\w\W]+?)$""")
try {
if (value != null) {
//字符串拼接
//value.concat("234556")
val lines = value.split("\n")
for (line <- lines) {
if ((pattern findAllIn line).mkString != null) {
if (line != ""){
var k = line.split("=")(0).replaceAll(" ", "")
var v = line.split("=")(1).replaceAll("=", "").replaceAll(" ", "")
cs += (k -> v)
}
}
}
}
}catch {
case e: Exception => {
println(s"!!!!!!!! " + e.getMessage)
}
}
cs
}
}
Object:
package main
import scala.io.Source
import libparser.conf
object bvs {
def main(args: Array[String]): Unit = {
// 读取配置文件
val content = Source.fromFile("/bvs/bvs.conf").getLines
val conf = new conf()
val confmap = conf.parser(content.mkString("\n"))
// Set(rulesfile, device2, writelocal, logfile, device1, interval)
// println(confmap.keys)
println(confmap("device2"))
}
}
Conf:
interval = 86400
writelocal = False
logfile = aaa.log
rulesfile = /aaaa/bbbb/eeeee
device1 = ("ip"->"***","port"->"22","username"->"root","password"->"***")
device2 = ("ip"->"***","port"->"22","username"->"root","password"->"***")