如何读取jar包外的properties文件和log4j.properties
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
時間有限,不做排版和具體講述問題產(chǎn)生的過程,下面是我的解決方案,已證實有效,其中Log4jP = "log4j.properties"
??private?void?initLog4jProperties(){//未打包時讀取配置String?file?=?this.getClass().getClassLoader().getResource(Log4jP).getFile();if(new?java.io.File(file).exists()){PropertyConfigurator.configure(file);System.out.println("未打包時讀取配置");return;}//讀取jar包外配置文件file?=?System.getProperty("user.dir")?+"/conf/"+Log4jP;????if(new?java.io.File(file).exists()){PropertyConfigurator.configure(file);System.out.println("讀取jar包外配置文件");return;}//讀取jar包內(nèi)配置文件InputStream?in?=?this.getClass().getClassLoader().getResourceAsStream(Log4jP);Properties?p=new?Properties();try?{p.load(in);PropertyConfigurator.configure(p);System.out.println("讀取jar包內(nèi)配置文件");}?catch?(IOException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}}參考內(nèi)容 如下?
轉(zhuǎn)自 http://jrails.iteye.com/blog/1705464
一般在項目中使用properties配置文件的時候都將相關(guān)的properties文件放在src目錄下,在將該app打包生成jar后,相應的properties配置文件生...
一般在項目中使用properties配置文件的時候都將相關(guān)的properties文件放在src目錄下,在將該app打包生成jar后,相應的properties配置文件生成在jar包中,這樣的話要修改配置文件又要重新打jar包,那是相當?shù)穆闊?
既然這么麻煩,你肯定想將配置文件放在其他的目錄下,生成的jar包內(nèi)不包含相應的配置文件,修改配置文件無需重新打包,沒錯,下面就是一種解決方案了。?
讀取jar包內(nèi)配置文件:
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));
另外,如果app中使用到log4j.properties文件,默認的存放路徑是src/log4j.properties,同上面一樣,我想把log4j.properties放在其他目錄中,這樣一來,在修改log4j配置文件的時候無需重新打jar包。?
在main函數(shù)第一行添加如下代碼:
PropertyConfigurator.configure(System.getProperty("user.dir")?+?"/conf/log4j.properties");轉(zhuǎn)載于:https://my.oschina.net/u/1866821/blog/507757
總結(jié)
以上是生活随笔為你收集整理的如何读取jar包外的properties文件和log4j.properties的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ceph的架构(一)
- 下一篇: EF修改对象里面的值。。。(对象字段多的