相信對于一名JAVA開發者開說properties文件一定再熟悉不過了,比如一下配置:
- config.properties會經常存放一些系統常量,版本號,路徑之類的
- database.properties存放數據庫的連接參數
- log4j.properties 日志的一些基本配置
- redis.properties 緩存數據庫的一些配置
當然前綴是根據用能自行定義的,一般來說文件的內容的格式是“鍵=值”的格式,文本注釋信息可以用”#”來注釋,下面來說說開發中如何讀寫properties配置文件。
Properties類讀取
Properties類繼承自Hashtable類并且實現了Map接口,也是使用一種鍵值對的形式來保存屬性集。不過Properties有特殊的地方,就是它的鍵和值都是字符串類型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//方式一 InputStream in = new BufferedInputStream( new FileInputStream( "文件路徑名" )); Properties p = new Properties(); p.load(in); System.out.println(p.getProperty( "version" )); //方式二 InputStream ins = PropertiesUtil. class .getResourceAsStream( "文件路徑名" ); Properties ps = new Properties(); ps.load(ins); System.out.println(ps.getProperty( "version" )); //方式三 InputStream inss = PropertiesUtil. class .getClassLoader().getResourceAsStream( "文件名" ); Properties pss = new Properties(); pss.load(inss); System.out.println(pss.getProperty( "version" )); //方式四 InputStream insss = ClassLoader.getSystemResourceAsStream( "文件名" ); Properties psss = new Properties(); psss.load(insss); System.out.println(pss.getProperty( "version" )); |
ResourceBundle讀取方式
這個類提供軟件國際化的捷徑。通過此類,可以使您所編寫的程序可以:
- 輕松地本地化或翻譯成不同的語言
- 一次處理多個語言環境
- 以后可以輕松地進行修改,支持更多的語言環境
說的簡單點,這個類的作用就是讀取資源屬性文件(properties),然后根據.properties文件的名稱信息(本地化信息),匹配當前系統的國別語言信息(也可以程序指定),然后獲取相應的properties文件的內容。
使用這個類,要注意的一點是,這個properties文件的名字是有規范的:一般的命名規范是: 自定義名語言代碼國別代碼.properties,如果是默認的,直接寫為:自定義名.properties
比如:
- myres_en_US.properties
- myres_zh_CN.properties
- myres.properties
1
2
3
4
5
6
7
|
//方式五 ResourceBundle rb = ResourceBundle.getBundle( "文件名前綴" , Locale.getDefault()); System.out.println(rb.getObject( "version" )); //方式六 InputStream is = new BufferedInputStream( new FileInputStream( "文件名前綴" )); ResourceBundle rbs = new PropertyResourceBundle(is); System.out.println(rbs.getObject( "version" )); |
ResourceBundle讀取方式,相對來說比較方便,但是仔細查看源碼,ResourceBundle讀取一次就會被系統緩存。
對于在生產環境中,如果我們要動態修改properties的一些參數,如果使用ResourceBundle讀取方式就必須要重啟服務器了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.52itstyle.com/archives/879/?utm_source=tuicool&utm_medium=referral