scala+Maven工程读取jar包外的配置文件

来源:互联网 发布:传奇荣耀辅助软件 编辑:程序博客网 时间:2024/06/11 21:49

我的笔记

程序中为了连接数据库,存在很多数据库的集群的信息,为了能让程序在不同的的集群中运行,需要到程序中更改集群数据库的配置。这里希望能将这些配置单独写成一个配置文件,方便迁移。在Windows系统下将配置信息直接写到resource目录下的配置文件(.properties文件)里即可,读取该conf.properties文件代码如下:
val properties = new Properties()val path = Thread.currentThread().getContextClassLoader.getResource("conf.properties").getPathproperties.load(new FileInputStream(path))val hbase_quorum = properties.getProperty("hbase_quorum")//"hbase_quorum"为conf.properties文件中键值名
此时通过clean、package的方法直接打包在Linux系统里运行的时候,报错表示找不到目录
Exception in thread "main" java.io.FileNotFoundException: file:/home/hadoop/test/app.jar!/conf.properties (No such file or directory)
而且这样配置文件会打包在jar包内,之后修改也会产生问题。如此我们希望能将conf.properties拿到与jar包同一级的目录下,让程序读取jar包外的文件。为此,考虑先得到系统路径,再找在改路径下的文件或者文件夹。这里我将conf.properties文件直接放在与jar同级目录下,读取jar包外文件代码如下:
val properties = new Properties()val filePath = System.getProperty("user.dir") + "/conf.properties"//获取系统路径和最终文件路径 properties.load(new FileInputStream(filePath))println(filePath)val hbase_quorum = properties.getProperty("hbase_quorum")//"hbase_quorum"为conf.properties文件中键值名
这样在打包的时候可以先将配置文件剪切出来,和jar包一起上传到Linux系统中同一目录下。在其他集群运行该jar包时只需要修改配置文件即可,不需要将代码重新打包上传。