1.Properties與ResourceBundle
兩個類都可以讀取屬性文件中以key/value形式存儲的鍵值對,ResourceBundle讀取屬性文件時操作相對簡單。
2.Properties
該類繼承Hashtable,將鍵值對存儲在集合中。基於輸入流從屬性文件中讀取鍵值對,load()方法調用完畢,就與輸入流脫離關係,不會自動關閉輸入流,需要手動關閉。
/**
* 基於輸入流讀取屬性文件:Properties繼承了Hashtable,底層將key/value鍵值對存儲在集合中,
* 通過put方法可以向集合中添加鍵值對或者修改key對應的value
*
* @throws IOException
*/
@SuppressWarnings("rawtypes")
@Test
public void test01() throws IOException {
FileInputStream fis = new FileInputStream("Files/test01.properties");
Properties props = new Properties();
props.load(fis);// 將文件的全部內容讀取到內存中,輸入流到達結尾
fis.close();// 加載完畢,就不再使用輸入流,程序未主動關閉,需要手動關閉
/*byte[] buf = new byte[1024];
int length = fis.read(buf);
System.out.println("content=" + new String(buf, 0, length));//拋出StringIndexOutOfBoundsException*/
System.out.println("driver=" + props.getProperty("jdbc.driver"));
System.out.println("url=" + props.getProperty("jdbc.url"));
System.out.println("username=" + props.getProperty("jdbc.username"));
System.out.println("password=" + props.getProperty("jdbc.password"));
/**
* Properties其他可能用到的方法
*/
props.put("serverTimezone", "UTC");// 底層通過hashtable.put(key,value)
props.put("jdbc.password", "456");
FileOutputStream fos = new FileOutputStream("Files/test02.xml");// 將Hashtable中的數據寫入xml文件中
props.storeToXML(fos, "來自屬性文件的數據庫連接四要素");
System.out.println();
System.out.println("遍歷屬性文件");
System.out.println("hashtable中鍵值對數目=" + props.size());
Enumeration keys = props.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
System.out.println(key + "=" + props.getProperty(key));
}
}
3.ResourceBundle
該類基於類讀取屬性文件:將屬性文件當作類,意味着屬性文件必須放在包中,使用屬性文件的全限定性類名而非路徑指代屬性文件。
/**
* 基於類讀取屬性文件:該方法將屬性文件當作類來處理,屬性文件放在包中,使用屬性文件的全限定性而非路徑來指代文件
*/
@Test
public void test02() {
ResourceBundle bundle = ResourceBundle.getBundle("com.javase.properties.test01");
System.out.println("獲取指定key的值");
System.out.println("driver=" + bundle.getString("jdbc.driver"));
System.out.println("url=" + bundle.getString("jdbc.url"));
System.out.println("username=" + bundle.getString("jdbc.username"));
System.out.println("password=" + bundle.getString("jdbc.password"));
System.out.println("-----------------------------");
System.out.println("遍歷屬性文件");
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println(key + "=" + bundle.getString(key));
}
}
4.讀取屬性文件到Spring容器
通常將數據庫連接四要素放在屬性文件中,程序從屬性文件中讀取參數,這樣當數據庫連接要素髮生改變時,不需要修改源代碼。將屬性文件中的內容加載到xml文檔中的方法:
- 在配置文件頭配置context約束。
- 在配置文件中加入<context:property-placeholder loacation="classpath:xxxxxx"/>,加載屬性到配置文件中。
- 獲取配置文件內容:${key}
5.註釋
#放在前面,用於在屬性文件中添加註釋。
6.編碼
屬性文件採用ISO-8859-1編碼方式,該編碼方式不支持中文,中文字符將被轉化爲Unicode編碼方式顯示。
關注公衆號:工控技術之家,可留言提問相關問題,有需要可發送源代碼