美文网首页我爱编程
java/scala 获取配置文件 properties

java/scala 获取配置文件 properties

作者: 点点渔火 | 来源:发表于2018-04-13 16:30 被阅读0次
java获取配置文件 properties
  • jar包的解压和压缩

    • 1、解压某个jar包:在需要解压的jar包目录下,按住shift建右击【在此处打开命令行】,输入:C:\jar>jar xf lm.jar 没有任何反应就表示解压成功。
    • 2、压缩jar包:命令:jar cvf lm.jar 文件1 文件2 文件3 文件4 压缩后的jar包就在本目录下,这样容易丢掉文件,可以 jar cvf lm.jar ./ 就全部压缩了
  • 未打jar包:
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包

打了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()
  }

}

相关文章

网友评论

    本文标题:java/scala 获取配置文件 properties

    本文链接:https://www.haomeiwen.com/subject/yathkftx.html