java.util.Properties 繼承自 Hashtable,專為「鍵值對」設定檔設計,支援從輸入流載入、輸出流儲存,並內建處理編碼、轉義、註解等細節,是 Java 應用程式外部化配置的經典選擇。
| 方法 | 用途 | 備註 |
|---|---|---|
load(InputStream) | 從位元組流載入 | ISO-8859-1 編碼,中文需轉碼 |
load(Reader) | 從字元流載入 (Java 6+) | 可直接指定 UTF-8 等編碼 |
store(OutputStream, comments) | 寫入位元組流 | 標頭註解可選 |
store(Writer, comments) | 寫入字元流 (Java 6+) | 支援 UTF-8 直接輸出 |
getProperty(key) / getProperty(key, defaultVal) | 取值 | 支援預設值 |
setProperty(key, value) | 設值 | 強制 String 鍵值,安全 |
stringPropertyNames() | 取得所有鍵 (String 集合) | 避免 Hashtable 遺留的非 String 鍵 |
import java.io.*;
import java.util.Properties;
public class PropertiesDemo {
private static final String FILE = "config.properties";
public static void main(String[] args) throws IOException {
Properties props = new Properties();
// 1. 讀取 (建議使用 Reader 指定 UTF-8)
try (Reader reader = new InputStreamReader(new FileInputStream(FILE), StandardCharsets.UTF_8)) {
props.load(reader);
} catch (FileNotFoundException e) {
System.out.println("配置檔不存在,將建立新檔");
}
// 2. 取值 (含預設值)
String siteName = props.getProperty("sitename", "DefaultSite");
String siteUrl = props.getProperty("siteurl", "https://localhost");
System.out.println("sitename = " + siteName);
System.out.println("siteurl = " + siteUrl);
// 3. 修改與新增 (僅接受 String)
props.setProperty("sitename", "Boxcode");
props.setProperty("studio", "Boxcode Studio");
// 4. 儲存 (使用 Writer 指定 UTF-8,避免中文亂碼)
try (Writer writer = new OutputStreamWriter(new FileOutputStream(FILE), StandardCharsets.UTF_8)) {
props.store(writer, "Copyright (c) Boxcode Studio - Updated: " + new Date());
}
// 5. 列出所有鍵值
props.stringPropertyNames().forEach(k ->
System.out.println(k + " = " + props.getProperty(k))
);
}
}
# 這是註解行
! 也是註解
sitename=Boxcode
siteurl=https://boxcode.example.com
studio=Boxcode Studio
# 布林值慣用 true/false
debug=true
# 數值需自行轉型
max.connections=100
load(InputStream) 固定用 ISO-8859-1,中文會變亂碼。必須改用 load(Reader) + InputStreamReader(..., StandardCharsets.UTF_8)。store() 拋出 ClassCastException。永遠使用 setProperty。Properties defaults = new Properties(); props = new Properties(defaults); 可實現預設值回退機制。ConcurrentHashMap 或讀取後快取不可變快照。