在使用Property和InputStream雹舀、OutputStream讀取配置文件時芦劣,使用try/catch捕獲IO異常時,發(fā)現(xiàn)下面的代碼
FileOutputStream fileOutputStream = null;
JSONObject object = new JSONObject();
try (InputStream inputStream = TestController.class.getResourceAsStream("application-dev.properties")){
URL url = TestController.class.getClassLoader().getResource("application-dev.properties");
fileOutputStream = new FileOutputStream(url.getPath());
Properties properties = new Properties();
if (!Objects.isNull(inputStream)){
properties.load(inputStream);
}
properties.setProperty("writeProperty3", "you made it!");
properties.store(fileOutputStream, "寫入屬性");
} finally {
// inputStream.close();
fileOutputStream.close();
}
try()里面的inputstream資源通過當前類.class.getResoureAsStream("xx")
時無法獲取说榆,而通過Thread.currentThread().getContextClassLoader().getResoureAsStream("xx")
可以獲取虚吟,有關解釋是如果你使用當前類.class.getClassLoader()
,可能會導致和當前線程所運行的類加載器不一致签财。
有時間再深入探究下串慰,先記錄下來。
參考鏈接