scala读取配置文件

2019-07-02 09:20:56 浏览数 (1)

Class:

代码语言:javascript复制
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 ([wW] ?)$""")
    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:

代码语言:javascript复制
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:

代码语言:javascript复制
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"->"***")

0 人点赞