我爱编程

java/scala 获取配置文件 properties

2018-04-13  本文已影响0人  点点渔火
java获取配置文件 properties
val properties = new Properties()

// 当前class的目录, 从当前执行类所在包目录开始查找资源
println(this.getClass.getResource(""))

// package的根目录
println(this.getClass.getResource("/param.properties"))

// package的根目录, 同上, 不能 "/", 默认就是从classpath下查找
println(this.getClass.getClassLoader.getResource(""))
// 同上
println(Thread.currentThread().getContextClassLoader.getResource("")

properties.load(new FileInputStream(path))

打了jar包后, 将properties文件放在src/main/resources目录下。就会自动打包到classes目录下。 上面的方式会找不到文件, 需要getResourceAsStream来获取配置文件

val properties = new Properties()

val in = Thread.currentThread().getContextClassLoader.getResourceAsStream("param.properties")

properties.load(in)

或者

val properties = new Properties()

val in = this.getClass.getClassLoader.getResourceAsStream("param.properties")

properties.load(in)

代码示例:
jar包外的配置文件可以通过store更改,jar包内的没办法更改

import java.io.{FileOutputStream, BufferedInputStream, InputStream, FileInputStream}
import java.util.Properties

object test {
  def main(args: Array[String]) {
   println("--" * 20)
    loadInnerProperties()
    println("**" * 20)
    loadOuterProperties()
  }

  //test.properties 里的内容为"ddd=5.6,1.2"
  def loadInnerProperties():Unit = {
    val properties = new Properties()
    val in = this.getClass.getClassLoader.getResourceAsStream("param.properties")
    //文件要放到resource文件夹下
    if (in != null) {
      properties.load(in)
      println(properties.getProperty("user"))
      val fos = new FileOutputStream("param2.properties")  //true表示追加打开
      properties.setProperty("address","beijing")//添加或修改属性值
      properties.store(fos, "address")
      fos.close()
    }
    else {
      println("读取不到配置文件")
    }
  }

    def loadOuterProperties():Unit = {
      val properties = new Properties()
      val in: InputStream = new BufferedInputStream (new FileInputStream("param2.properties"))
      properties.load(in)
      println(properties.getProperty("user"))
      val fos = new FileOutputStream("param2.properties", false)
      //可选参数append 默认false 覆盖写, true则后面添加
      properties.setProperty("address","beijing")//添加或修改属性值
      properties.store(fos, "address")
      fos.close()
  }

}
上一篇 下一篇

猜你喜欢

热点阅读