Java Properties 類
Properties 繼承於 Hashtable.表示一個持久的屬性集.屬性列表中每個鍵及其對應值都是一個字串。
Properties 類被許多Java類使用。例如,在獲取環境變數時它就作為System.getProperties()方法的返回值。
Properties 定義如下實例變數.這個變數持有一個Properties對象相關的默認屬性列表。
Properties defaults;
Properties類定義了兩個構造方法. 第一個構造方法沒有默認值。
Properties()
第二個構造方法使用propDefault 作為默認值。兩種情況下,屬性列表都為空:
Properties(Properties propDefault)
除了從Hashtable中所定義的方法,Properties定義了以下方法:
序號 | 方法描述 |
---|---|
1 |
String getProperty(String key) 用指定的鍵在此屬性列表中搜索屬性。 |
2 |
String getProperty(String key, String defaultProperty) 用指定的鍵在屬性列表中搜索屬性。 |
3 |
void list(PrintStream streamOut) 將屬性列表輸出到指定的輸出流。 |
4 |
void list(PrintWriter streamOut) 將屬性列表輸出到指定的輸出流。 |
5 |
void load(InputStream streamIn) throws IOException 從輸入流中讀取屬性列表(鍵和元素對)。 |
6 |
Enumeration propertyNames( ) 按簡單的面向行的格式從輸入字元流中讀取屬性列表(鍵和元素對)。 |
7 |
Object setProperty(String key, String value) 調用 Hashtable 的方法 put。 |
8 |
void store(OutputStream streamOut, String description) 以適合使用 load(InputStream)方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流。 |
實例
下麵的程式說明這個數據結構支持的幾個方法:
實例
import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " +
str + " is " + capitals.getProperty(str) + ".");
}
System.out.println();
// look for state not in list -- specify default
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is "
+ str + ".");
}
}
以上實例編譯運行結果如下:
The capital of Missouri is Jefferson City. The capital of Illinois is Springfield. The capital of Indiana is Indianapolis. The capital of California is Sacramento. The capital of Washington is Olympia. The capital of Florida is Not Found.