一、概述
java.util.Properties集合 extends Hashtable<k,v> implements Map<k,v>
java.util.Properties 繼承與 Hashtable,來表示一個持久的屬性集。
Properties 可保存在流中或從流中加載,Properties集合是一個唯一和IO流相結合的集合。
它使用鍵值結構存儲數據,屬性列表中每個鍵及其對應值都是一個字符串。Properties集合是一個雙列集合,key和value默認都是字符串
二、Properties 類
1、構造方法
public Properties() :創建一個空的屬性列表
2、基本的存儲方法
public Object setProperty(String key, String value) : 保存一對屬性。
public String getProperty(String key) :使用此屬性列表中指定的鍵搜索屬性值。
public Set<String> stringPropertyNames() :所有鍵的名稱的集合,其中該鍵及其對應值是字符串。
Demo:
1 public static void main(String[] args) throws IOException { 2 //創建Properties集合對象
3 Properties prop = new Properties(); 4 //使用setProperty往集合中添加數據,都是字符串
5 prop.setProperty("張三","16"); 6 prop.setProperty("李四","17"); 7 prop.setProperty("王五","18"); 8 //prop.put(1,true); 9
10 //使用stringPropertyNames把Properties集合中的鍵取出,存儲到一個Set集合中
11 Set<String> set = prop.stringPropertyNames(); 12
13 //遍歷Set集合,取出Properties集合的每一個鍵
14 for (String key : set) { 15 //使用getProperty方法通過key獲取value
16 String value = prop.getProperty(key); 17 System.out.println(key+"="+value); 18 } 19
3、與流相關的方法
(1)使用 store 方法,存儲數據
使用Properties集合中的方法store,把集合中的臨時數據,持久化寫入到硬盤中存儲
void store(OutputStream out, String comments)
void store(Writer writer, String comments)
參數:
OutputStream out:字節輸出流,不能寫入中文
Writer writer:字符輸出流,可以寫中文
String comments:注釋,用來解釋說明保存的文件是做什么的,不能使用中文,會產生亂碼,默認是 Unicode編碼,一般使用“” 空字符串。
使用步驟:
① 創建 Properties 對象,添加數據
② 創建字節輸出流 / 字符輸出流對象,構造方法中綁定要輸出的目的地。
③ 使用 Properties 集合中的方法 store,把集合中的臨時數據,持久化寫入到硬盤中存儲
④ 釋放資源。
Demo:
1 public static void main(String[] args) throws IOException { 2 //1.創建Properties集合對象,添加數據
3 Properties prop = new Properties(); 4 prop.setProperty("張三","16"); 5 prop.setProperty("李四","17"); 6 prop.setProperty("王五","18"); 7
8 //2.創建字節輸出流/字符輸出流對象,構造方法中綁定要輸出的目的地 9 FileWriter fw = new FileWriter("E:\\prop.txt"); 10
11 //3.使用Properties集合中的方法store,把集合中的臨時數據,持久化寫入到硬盤中存儲 12 prop.store(fw,"save data"); 13
14 //4.釋放資源 15 fw.close();
16
17 //prop.store(new FileOutputStream("E:\\prop2.txt"),""); // 寫入中文后亂碼 18 }
(2)使用 load 方法,讀取數據
使用Properties集合中的方法load,把硬盤中保存的文件(鍵值對),讀取到集合中使用
void load(InputStream inStream)
void load(Reader reader)
參數:
InputStream inStream:字節輸入流,不能讀取含有中文的鍵值對
Reader reader:字符輸入流,能讀取含有中文的鍵值對
使用步驟:
① 創建 Properties 集合對象
② 使用Properties集合對象中的方法load讀取保存鍵值對的文件
③ 遍歷Properties集合
注意:
① 存儲鍵值對的文件中,鍵與值默認的連接符號可以使用=,空格(其他符號)
② 存儲鍵值對的文件中,可以使用#進行注釋,被注釋的鍵值對不會再被讀取
③ 存儲鍵值對的文件中,鍵與值默認都是字符串,不用再加引號
Demo:
1 public static void main(String[] args) throws IOException { 2 //1.創建Properties集合對象
3 Properties prop = new Properties(); 4 //2.使用Properties集合對象中的方法load讀取保存鍵值對的文件
5 prop.load(new FileReader("E:\\prop.txt")); 6 //prop.load(new FileInputStream("E:\\prop.txt")); 獲取亂碼 7 //3.遍歷Properties集合
8 Set<String> set = prop.stringPropertyNames(); 9 for (String key : set) { 10 String value = prop.getProperty(key); 11 System.out.println(key+"="+value); 12 } 13 }
