Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤和異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 和框架

Java 類引用

Java 有用資源

Java - Properties 類



Properties 是 Hashtable 的子類。它用於維護值列表,其中鍵是字串,值也是字串。

許多其他 Java 類都使用 Properties 類。例如,它是 System.getProperties() 在獲取環境值時返回的物件型別。

Properties 定義了以下例項變數。此變數儲存與 Properties 物件關聯的預設屬性列表。

Properties defaults;

以下是 Properties 類提供的建構函式列表。

序號 建構函式和說明
1

Properties()

此建構函式建立一個沒有預設值的 Properties 物件。

2

Properties(Properties propDefault)

建立一個使用 propDefault 作為其預設值的物件。在這兩種情況下,屬性列表都是空的。

除了 Hashtable 定義的方法外,Properties 還定義了以下方法:

序號 方法和說明
1

String getProperty(String key)

返回與鍵關聯的值。如果鍵既不在列表中也不在預設屬性列表中,則返回 null 物件。

2

String getProperty(String key, String defaultProperty)

返回與鍵關聯的值;如果鍵既不在列表中也不在預設屬性列表中,則返回 defaultProperty。

3

void list(PrintStream streamOut)

將屬性列表傳送到與 streamOut 連結的輸出流。

4

void list(PrintWriter streamOut)

將屬性列表傳送到與 streamOut 連結的輸出流。

5

void load(InputStream streamIn) throws IOException

從與 streamIn 連結的輸入流輸入屬性列表。

6

Enumeration propertyNames()

返回鍵的列舉。這也包括在預設屬性列表中找到的那些鍵。

7

Object setProperty(String key, String value)

將 value 與 key 關聯。返回以前與 key 關聯的值,如果不存在這樣的關聯,則返回 null。

8

void store(OutputStream streamOut, String description)

寫入 description 指定的字串後,屬性列表將寫入與 streamOut 連結的輸出流。

示例

以下程式說明了此資料結構支援的幾種方法:

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.
java_data_structures.htm
廣告
© . All rights reserved.