java 4種方式讀取配置檔案 修改配置檔案

2021-07-25 00:17:51 字數 2400 閱讀 8526

因為是用

servletcontext

讀取檔案路徑,所以配置檔案可以放入在

web-info

的classes

目錄中,也可以在應用層級及

web-info

的目錄中。檔案存放位置具體在

eclipse

工程中的表現是:可以放在

src下面,也可放在

web-info

及webroot

下面等。因為是讀取出路徑後,用檔案流進行讀取的,所以可以讀取任意的配置檔案包括

xml和

properties

。缺點:不能在

servlet

外面應用讀取配置資訊。

具體舉例如下:

讀取路徑

優點是:可以以完全限定類名的方式載入資源後,直接的讀取出來,且可以在非

web應用中讀取資源檔案。

缺點:只能載入類

classes

下面的資源檔案且只能讀取

.properties

檔案。

/**

* 獲取指定配置檔案中所以的資料

* @param propertyname

* 呼叫方式:

* 1.配置檔案放在resource源包下,不用加字尾

* propertiesutil.getallmessage("message");

* 2.放在包裡面的

* propertiesutil.getallmessage("com.test.message");

* @return

*/public static listgetallmessage(string propertyname)

return vallist;

}

優點是:可以在非web應用中讀取配置資源資訊,

可以讀取任意的資源檔案資訊

缺點:只能載入類classes下面的資源檔案。

/**獲取的是class的根路徑下的檔案

* 優點是:可以在非web應用中讀取配置資源資訊,可以讀取任意的資源檔案資訊

* 缺點:只能載入類classes下面的資源檔案。

* 如果要加上路徑的話:com/test/servlet/jdbc_connection.properties

*/private static void use_classloador() catch (ioexception e)

}

xmlparserhandler.class.getresourceasstream 與classloader不同

使用的是當前類的相對路徑

bufferedreader br=new bufferedreader(    

new inputstreamreader(xmlparserhandler.class.

getresourceasstream("./rain.xml"), "gb2312"));// ./代表當前目錄不寫也可以

inputsource is=new inputsource(br);//資料來源

/**

* spring 提供的 propertiesloaderutils 允許您直接通過基於類路徑的檔案位址載入屬性資源

* 最大的好處就是:實時載入配置檔案,修改後立即生效,不必重啟

*/private static void springutil()

} catch (ioexception e)

try catch (interruptedexception e)

} }

/**

* 傳遞鍵值對的map,更新properties檔案

* * @param filename

* 檔名(放在resource源包目錄下),需要字尾

* @param keyvaluemap

* 鍵值對map

*/public static void updateproperties(string filename,mapkeyvaluemap) catch (ioexception e) finally catch (ioexception e)

} }

java 4種方式讀取配置檔案 修改配置檔案

因為是用 servletcontext 讀取檔案路徑,所以配置檔案可以放入在 web info 的classes 目錄中,也可以在應用層級及 web info 的目錄中。檔案存放位置具體在 eclipse 工程中的表現是 可以放在 src下面,也可放在 web info 及webroot 下面等。因...

Java 讀取配置檔案的方式

通過乙個propertiesutil類,在tomcat初始化時,對properties物件props進行初始化 指向對應的配置檔案filename mmall public class propertiesutil catch ioexception e public static string g...

java 讀取配置檔案

前幾天因為配置檔案的事,線上的job掛掉了,使用的是spring載入配置檔案方式。spring配置如下 test.properties api test.properties decryptpropertyplaceholderconfigurer類如下所示。public class decrypt...