Java中動態載入properties檔案,而不需要重啟應用的解決辦法
在Java專案中,如果需要使用.properties型別的檔案作為某些配置資訊存放介質的時候,一般都是將.properties檔案放在src目錄下,程式碼大部分都是這樣寫的:
Properties prop = new Properties();
InputStream is = CommonUtils.class.getClassLoader().getResourceAsStream("config.properties");//假設當前這個方法是在CommonUtils類下面
prop.load(is);
在系統啟動之後,config.properties中的key-value資訊都可以獲取,但是某一天,你想改變一下config.properties中的相關配置,但是又不能重啟應用,你就會發現,明明已經修改了config.properties檔案內容,為什麼讀出來的資訊還是原先的?
經過google後發現,原來使用:
CommonUtils.class.getClassLoader().getResourceAsStream("config.properties")
這種載入方法會將config.properties檔案載入到記憶體中,在下次需要讀取時直接從記憶體中獲取檔案資訊,而不是再次讀取!
既然以上方法會將檔案資訊快取,那麼我只要改變一下檔案的輸入流獲取方式就行了。
改成如下方式就行了:
Properties prop = new Properties();
String path = CommonUtils.class.getClassLoader().getResource("config.properties").getPath();
InputStream is = new FileInputStream(path);
prop.load(is);
或者
String dirPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();//獲取config.properties檔案所在的父目錄
File file = new File(dirPath,"config.properties");
注意:在使用過程中遇到這樣一個問題,mark一下---》我再static方法裡面用讀取properties(使用不用重啟的方法讀取),但是修改properties檔案後,發現不生效,後來發現是static的原因。(有關static大家可以百度瞭解)
轉載:http://www.myexception.cn/internet/1484938.html