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)); } }
以下代碼,可以通過相對路徑讀取properties文件:
Properties props= new Properties(); // 通過類加載器進行獲取properties文件流,路徑為相對路徑 InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream(jdbc.properties); props.load(in);
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)); } }
參考博客: