前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >scala的maven项目读取配置文件

scala的maven项目读取配置文件

作者头像
用户1171305
发布2017-12-28 11:26:26
2.9K0
发布2017-12-28 11:26:26
举报
文章被收录于专栏:成长道路成长道路

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

结果截图:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-04-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档