scala的maven项目读取src/main/resources目录下的资源文件该如何读取呢?
下面提供一种默认的和一种自定义的:
对于application.conf配置文件,是默认的配置文件:
application.conf内容如下:
mysql { url : "jdbc:mysql://192.168.76.14:3306/ibigdata?useUnicode=true&characterEncoding=UTF-8", dbtable: "record_test", user: "root", password:"root" }
SparkConfig.scala的读取配置文件内容的代码如下:
package com.iflytek.rwresourcefile
import com.typesafe.config.Config import com.typesafe.config.ConfigFactory
object SparkConfig extends java.io.Serializable{ val config:Config=ConfigFactory.load() def getString(path:String):String={ return config.getString(path) } def getInteger(path:String):Integer={ return config.getString(path).toInt } def getDouble(path:String):Double={ return config.getString(path).toDouble } }
Test.scala的测试代码如下:
package com.iflytek.rwresourcefile
import org.apache.spark.SparkConf
object Test { def main(args: Array[String]): Unit = { val url=SparkConfig.getString("mysql.url") val dbtable=SparkConfig.getString("mysql.dbtable") val user=SparkConfig.getString("mysql.user") val password=SparkConfig.getString("mysql.password") println("url="+url) println("dbtable="+dbtable) println("user="+user) println("password="+password) } }
截图:
对于mysql.conf这种自定义的配置文件的读取方式如下:
url=jdbc:mysql://192.168.76.14:3306/ibigdata?useUnicode=true&characterEncoding=UTF-8 dbtable=record_test user=root password=root
PropertieUtil.scala的读取自定义配置文件的代码如下:
package com.iflytek.rwresourcefile
import java.util.Properties import java.io.InputStreamReader
object PropertieUtil extends java.io.Serializable{ def getpropertie(path:String):Properties={ val properties:Properties=new Properties val in:InputStreamReader=new InputStreamReader(PropertieUtil.getClass.getClassLoader.getResourceAsStream(path),"utf-8") properties.load(in) return properties } val propertie=getpropertie("mysql.conf") def getStrign(path:String):String={ return propertie.getProperty(path) } }
test111.scala的测试代码如下:
package com.iflytek.rwresourcefile
object test111 { def main(args: Array[String]): Unit = { val url=PropertieUtil.getStrign("url") val dbtable=PropertieUtil.getStrign("dbtable") val user=PropertieUtil.getStrign("user") val password=PropertieUtil.getStrign("password") println("url="+url) println("dbtable="+dbtable) println("user="+user) println("password"+password) } }
结果截图: