如何读取JAR包外的properties文件及打成jar包后无法读取到jar包内的properties文件

来源:互联网 发布:h5微社区源码 编辑:程序博客网 时间:2024/06/09 08:56
打成jar包后无法读取到jar包内的properties文件
发现在eclipse里一切正常,但打成jar包后就无法读取到properties文件了。
之前的程序是这样获取配置文件的:
Thread.currentThread().getContextClassLoader().getResource("").getPath() +filename+".properties")  

来获取properties文件,但发现一运行就报错.后来将代码改成:
this.getClass().getClassLoader().getResourceAsStream(filename+".properties")

一切正常~
关于java 的 classloader 还是有点概念不清,需要补补~~

一般在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要重新打jar包,那是相当的麻烦。。
既然这么麻烦,你肯定想将配置文件放在其他的目录下,生成的jar包内不包含相应的配置文件,修改配置文件无需重新打包,没错,下面就是一种解决方案了。
读取jar包内配置文件:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");  

读取jar包外配置文件:
String filePath = System.getProperty("user.dir") + "/conf/configfilename.properties";     InputStream in = new BufferedInputStream(new FileInputStream(filePath));   

原地址:http://hi.baidu.com/qu3999352/item/04361a620a28fb2b69105b92
阅读全文
0 0
原创粉丝点击