Properties類的概述(集合)
1. Properties類的特點:
1) 屬性列表(鍵和值)中每個鍵及其對應值都是一個字符串
2) 可保存在流中或從流中加載,可以對IO流進行操作。把屬性集合存到文件中,或從文件中讀取所有的屬性。
2. 屬性文件的格式要求:
屬性文件中不能直接漢字,所有的漢字會轉成Unicode編碼
1) 格式:屬性名=屬性值
2) 每個屬性占一行
3) 注釋:以#號開頭的行是注釋行
4) 屬性文件中所有空行被忽略
5) 擴展名:properties
常用的方法
1. 構造方法:使用無參的構造方法 new Properties(),創建了一個空的集合。
2. 設置/得到屬性值:
不建議使用從Map中繼承下來的put()/get()方法添加/獲得元素,因為put()可能添加非字符串類型的數據。
● 添加屬性值:setProperty(屬性名, 屬性值)
● 得到屬性值:String getProperty("屬性名"),如果沒有屬性,則返回null
String getProperty("屬性名", "默認值") 始終保證可以得到一個非空的值
遍歷的方法,得到所有的屬性名stringPropertyNames()
將集合中內容存儲到文件
1. 保存到IO流:(字節流,字符流)
store(OutputStream 字節輸出流, String 注釋)
store(Writer 字符輸出流, String 注釋)
View Code@Test public void testPropertiesSave() throws IOException { //創建屬性集 Properties prop = new Properties(); prop.setProperty("name", "Jack"); prop.setProperty("age", "18"); prop.setProperty("gender", "male"); //寫到FileOutputStream字節輸出流 FileOutputStream fos = new FileOutputStream("d:/emp.properties"); prop.store(fos, "I am a employee");//寫到io流中 fos.close(); }2. 讀取文件中的數據,並保存到屬性集合
1. 從流中加載:
load(InputStream 字節輸入流)
load(Reader 字符輸入流)
View Code@Test public void testLoad() throws IOException { //創建一個空的集合 Properties properties = new Properties(); //創建一個文件輸入流 FileInputStream fis = new FileInputStream("d:/emp.properties"); properties.load(fis); System.out.println(properties); //關閉流 fis.close(); }