java.util.Properties 繼承 Hashtable<Object, Object>,可用 Map 介面方法遍歷,也有專屬 propertyNames()。
Properties props = new Properties();
try (InputStream in = ClassLoader.getSystemResourceAsStream("wahaha.properties")) {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
name1=xxxx
name2=yyyyy
name3=zzzzzzz
Enumeration<?> keys = props.propertyNames(); // 僅返回 String 鍵
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
System.out.println("Key: " + key);
// 取值:props.getProperty(key)
}
輸出:
Key: name1
Key: name2
Key: name3
Enumeration<String> (實際為 Enumeration<?>),類型安全。Enumeration<?> values = props.elements(); // 返回所有值 (Object)
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
System.out.println("Value: " + value);
}
輸出:
Value: xxxx
Value: yyyyy
Value: zzzzzzz
ClassCastException。for (Map.Entry<Object, Object> entry : props.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + " = " + value);
}
輸出:
name1 = xxxx
name2 = yyyyy
name3 = zzzzzzz
Set<Map.Entry<Object, Object>>,可同時獲取鍵值。Object,需轉型或 toString()。| 方法 | 返回類型 | 可獲取鍵 | 可獲取值 | 類型安全 | 適用場景 |
|---|---|---|---|---|---|
| propertyNames() | Enumeration | ✅ | 需額外 getProperty | 鍵為 String | 僅需遍歷鍵名 |
| elements() | Enumeration | ❌ | ✅ | 值為 String | 僅需遍歷值 |
| entrySet() | Set<Entry> | ✅ | ✅ | Object (需轉型) | 需同時處理鍵值 (最常用) |
// 僅字串鍵值
props.stringPropertyNames().stream()
.forEach(key -> System.out.println(key + "=" + props.getProperty(key)));
// 完整 Entry Stream
props.entrySet().stream()
.forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
entrySet() 或 stringPropertyNames()**:API 清晰、支援 Stream。elements():無法獲取鍵、類型不安全。ConcurrentModificationException;需先收集鍵再操作。load(Reader) 支援 UTF-8;舊版需自行轉碼 (ISO-8859-1 → UTF-8)。