一.屬性集
1.概述
java.util.Properties 繼承于Hashtable ,來表示一個持久的屬性集。它使用鍵值結構存儲資料,每個鍵及其對應值都是一個字元串。該類也被許多Java類使用,比如擷取系統屬性時,System.getProperties 方法就是傳回一個Properties對象。
2.Properties類
構造方法
- public Properties() :建立一個空的屬性清單。
基本的存儲方法
- public Object setProperty(String key, String value) : 儲存一對屬性。
- public String getProperty(String key) :使用此屬性清單中指定的鍵搜尋屬性值。
- public Set stringPropertyNames() :所有鍵的名稱的集合。
public class ProDemo {
public static void main(String[] args) throws FileNotFoundException {
// 建立屬性集對象
Properties properties = new Properties();
// 添加鍵值對元素
properties.setProperty("filename", "a.txt");
properties.setProperty("length", "209385038");
properties.setProperty("location", "D:\\a.txt");
// 列印屬性集對象
System.out.println(properties);
// 通過鍵,擷取屬性值
System.out.println(properties.getProperty("filename"));
System.out.println(properties.getProperty("length"));
System.out.println(properties.getProperty("location"));
// 周遊屬性集,擷取所有鍵的集合
Set<String> strings = properties.stringPropertyNames();
// 列印鍵值對
for (String key : strings ) {
System.out.println(key+" -- "+properties.getProperty(key));
}
}
}
輸出結果:
{filename=a.txt, length=209385038, location=D:\a.txt}
a.txt
209385038
D:\a.txt
filename -- a.txt
length -- 209385038
location -- D:\a.txt
3.與流相關的方法
- public void load(InputStream inStream): 從位元組輸入流中讀取鍵值對。
參數中使用了位元組輸入流,通過流對象,可以關聯到某檔案上,這樣就能夠加載文本中的資料了。
文本資料格式:
filename=a.txt
length=209385038
location=D:\a.txt
public class ProDemo2 {
public static void main(String[] args) throws FileNotFoundException {
// 建立屬性集對象
Properties pro = new Properties();
// 加載文本中資訊到屬性集
pro.load(new FileInputStream("read.txt"));
// 周遊集合并列印
Set<String> strings = pro.stringPropertyNames();
for (String key : strings ) {
System.out.println(key+" -- "+pro.getProperty(key));
}
}
}
輸出結果:
filename -- a.txt
length -- 209385038
location -- D:\a.txt
文本中的資料,必須是鍵值對形式,可以使用空格、等号、冒号等符号分隔。