Scala读取application.properties文件内容

tech2025-09-10  31

application.properties

application.properties文件位于resources目录下

lpf=123 #kudu.master=10.101.15.229,10.101.15.230,10.101.15.231 kudu.master=szbigdata01,szbigdata02,szbigdata03 health_assess_data_table=health_assess_data group_health_assess_result_table=group_health_assess_result base_tag_table=base_tag rule_tag_map_table=rule_tag_map

ReadPropFileUtil

package org.fiend.scalatest.util import java.io.{BufferedInputStream, File, FileInputStream, IOException, InputStream} import java.util.Properties import org.apache.commons.lang3.StringUtils object ReadPropFileUtil { def main(args: Array[String]): Unit = { println("kudu.master: " + readProp("kudu.master")) println("lpf: " + readProp("lpf")) } @throws[IOException] def readProp(name: String): String = { val prop = new Properties // 获取jar包内部或开发环境中resource文件夹下的文件 val in0 = ReadPropFileUtil.getClass.getClassLoader.getResourceAsStream("application.properties") prop.load(in0) loadCurrPathProp(prop) val propVal = prop.getProperty(name) if (null == propVal) { throw new NullPointerException("read properties key={" + name + "} is null!") } propVal } /** * 加载 当前工程目录(或jar包所在目录)下的application.properties文件, * 且读取该文件优先级较高, 即该文件内容若与jar包内(或工程内)的application.properties文件内容冲突 * , 则最终读取该文件相应的内容 * * @param prop p */ @throws[IOException] private def loadCurrPathProp(prop: Properties): Unit = { val osName = System.getProperty("os.name") var fileName: String = null if (StringUtils.containsIgnoreCase(osName, "Windows")) { fileName = System.getProperty("user.dir") + "\\application.properties" } else { fileName = System.getProperty("user.dir") + "/application.properties" } val file = new File(fileName) if (file.exists) { val in = new BufferedInputStream(new FileInputStream(file)) prop.load(in) } } // def readProp0(name: String): String = { // val properties = new Properties() // val path = Thread // .currentThread() // .getContextClassLoader // .getResource("application.properties") // .getPath //文件要放到resource文件夹下 // properties.load(new FileInputStream(path)) // // val propVal = properties.getProperty(name) // if (null == propVal) { // throw new NullPointerException("read properties key={" + name + "} is null!") // } // // propVal // } }

 

最新回复(0)