java.util.Properties 陪伴 Java 多年,Java 5 (Tiger) 為其注入兩大強化:
key=value(以分隔符分割)loadFromXML(InputStream) / storeToXML(OutputStream, String)無需再引入 DOM/SAX 解析器處理配置文件,標準庫一行搞定。
foo=bar
fu=baz
載入範例:
Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("sample.properties")) {
prop.load(fis);
}
System.out.println(prop.getProperty("foo")); // bar
注意:Properties 繼承 Hashtable,**順序不保證**。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "https://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<comment>配置文件說明</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>
<properties>,屬性 version="1.0" 固定<comment>,多個 <entry key="...">value</entry>// 載入 XML
Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("config.xml")) {
prop.loadFromXML(fis);
}
// 儲存為 XML
try (FileOutputStream fos = new FileOutputStream("config.xml")) {
prop.storeToXML(fos, "應用配置 - 自動生成");
}
| 維度 | 傳統 .properties | XML 格式 |
|---|---|---|
| 結構表達 | 扁平鍵值 | 層次化、可嵌套註釋 |
| 編碼處理 | ISO-8859-1 需轉義 | 原生 UTF-8/指定編碼 |
| 工具支援 | 文本編輯器 | XML 編輯器、Schema 驗證、XSLT 轉換 |
| 程式碼量 | 手寫解析器 | 零代碼(兩行 API) |
.properties.xmlJava 5 讓配置管理更標準、更強大,升級專案時別忘了遷移舊配置!