| 1.Properties與ResourceBundle兩個(gè)類都可以讀取屬性文件中以key/value形式存儲(chǔ)的鍵值對(duì),ResourceBundle讀取屬性文件時(shí)操作相對(duì)簡(jiǎn)單。 2.Properties該類繼承Hashtable,將鍵值對(duì)存儲(chǔ)在集合中?;谳斎肓鲝膶傩晕募凶x取鍵值對(duì),load()方法調(diào)用完畢,就與輸入流脫離關(guān)系,不會(huì)自動(dòng)關(guān)閉輸入流,需要手動(dòng)關(guān)閉。 /** * 基于輸入流讀取屬性文件:Properties繼承了Hashtable,底層將key/value鍵值對(duì)存儲(chǔ)在集合中, * 通過(guò)put方法可以向集合中添加鍵值對(duì)或者修改key對(duì)應(yīng)的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);// 將文件的全部?jī)?nèi)容讀取到內(nèi)存中,輸入流到達(dá)結(jié)尾 fis.close();// 加載完畢,就不再使用輸入流,程序未主動(dòng)關(guān)閉,需要手動(dòng)關(guān)閉 /*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");// 底層通過(guò)hashtable.put(key,value) props.put("jdbc.password", "456"); FileOutputStream fos = new FileOutputStream("Files/test02.xml");// 將Hashtable中的數(shù)據(jù)寫(xiě)入xml文件中 props.storeToXML(fos, "來(lái)自屬性文件的數(shù)據(jù)庫(kù)連接四要素"); System.out.println(); System.out.println("遍歷屬性文件"); System.out.println("hashtable中鍵值對(duì)數(shù)目=" + props.size()); Enumeration keys = props.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); System.out.println(key + "=" + props.getProperty(key)); } } 3.ResourceBundle該類基于類讀取屬性文件:將屬性文件當(dāng)作類,意味著屬性文件必須放在包中,使用屬性文件的全限定性類名而非路徑指代屬性文件。 /** * 基于類讀取屬性文件:該方法將屬性文件當(dāng)作類來(lái)處理,屬性文件放在包中,使用屬性文件的全限定性而非路徑來(lái)指代文件 */ @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容器通常將數(shù)據(jù)庫(kù)連接四要素放在屬性文件中,程序從屬性文件中讀取參數(shù),這樣當(dāng)數(shù)據(jù)庫(kù)連接要素發(fā)生改變時(shí),不需要修改源代碼。將屬性文件中的內(nèi)容加載到xml文檔中的方法: 
 5.注釋#放在前面,用于在屬性文件中添加注釋。 6.編碼屬性文件采用ISO-8859-1編碼方式,該編碼方式不支持中文,中文字符將被轉(zhuǎn)化為Unicode編碼方式顯示。 | 
|  | 
來(lái)自: 忠波irlphwt1ng > 《java》