Properties集合是唯一一個可以和IO流相結合的集合
可以將集合中的數據持久化存儲,也可以將硬盤上的數據加載到該集合中。
1 Properties集合添加、遍歷
1 private static void show01() { 2 // setProperty() 通過該方法向Properties內添加一對字符串鍵值對 3 Properties properties = new Properties(); 4 properties.setProperty("kelvin", "180"); 5 properties.setProperty("jack", "168"); 6 properties.setProperty("siri", "170"); 7 8 // stringPropertyNames() 通過該方法獲取Properties集合內的所有鍵組成的set集合 9 Set<String> strings = properties.stringPropertyNames(); 10 for (String key : strings) { 11 String value = properties.getProperty(key); 12 System.out.println(key + "--" + value); 13 } 14 }
2 Properties的store()方法持久化集合數據
1 // store() 持久化數據 2 private static void show02() throws IOException { 3 /* 4 持久化數據步驟: 5 1 創建Properties對象,存儲數據 6 2 創建字節輸出流/字符輸出流對象,指定將數據持久化的位置(字節流不能持久化中文) 7 3 調用Properties對象的save()方法,將集合中的臨時數據持久化到指定位置 8 4 釋放資源 9 */ 10 Properties properties = new Properties(); 11 properties.setProperty("kelvin", "180"); 12 properties.setProperty("jack", "168"); 13 properties.setProperty("siri", "170"); 14 15 FileWriter fw = new FileWriter("prop.txt"); 16 properties.store(fw, "store data"); 17 fw.close(); 18 }
3 Properties 的load()方法加載文件數據到集合
1 /* 2 加載數據步驟: 3 1 創建Properties對象 4 2 調用load方法加載指定文件 5 3 遍歷Properties集合 6 注意事項: 7 1 存儲鍵值對的文件中,可以使用=,空格或其他符號進行連接 8 2 存儲鍵值對的文件中,可以使用#進行注釋,注釋內容不會加載 9 3 讀取內容默認是字符串格式 10 */ 11 private static void show03() throws IOException { 12 Properties properties = new Properties(); 13 properties.load(new FileReader("prop.txt")); 14 Set<String> strings = properties.stringPropertyNames(); 15 for (String key : strings) { 16 String value = properties.getProperty(key); 17 System.out.println(key + "--" + value); 18 } 19 20 }
# 注:在load或store方法中使用字節流或字符流的匿名對象無需釋放資源。