Properties 核心特性
- 繼承
Hashtable,鍵值對存儲,鍵值均為 String
- 支援默認屬性列表鏈式查找
- 提供
load(InputStream) 讀取、store(OutputStream, String) 寫入
- 強制使用
setProperty/getProperty 避免非字符串污染
基本操作流程
1. 讀取屬性文件
Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("prop.properties")) {
prop.load(fis);
}
2. 獲取屬性值
String site = prop.getProperty("sitename"); // 存在返回值
String country = prop.getProperty("country", "中國"); // 不存在返回默認值
3. 修改與新增
prop.setProperty("sitename", "Boxcode"); // 修改
prop.setProperty("studio", "Boxcode Studio"); // 新增
4. 持久化保存
try (FileOutputStream fos = new FileOutputStream("prop.properties")) {
prop.store(fos, "Copyright (c) Boxcode Studio"); // 註釋行
}
完整示例程序
public class PropertyEditor {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("prop.properties")) {
prop.load(fis);
}
System.out.println("sitename=" + prop.getProperty("sitename"));
System.out.println("country=" + prop.getProperty("country", "中國"));
prop.setProperty("sitename", "Boxcode");
prop.setProperty("studio", "Boxcode Studio");
try (FileOutputStream fos = new FileOutputStream("prop.properties")) {
prop.store(fos, "Copyright (c) Boxcode Studio");
}
}
}
關鍵注意事項
- 編碼問題:JDK 9+
load/store 默認 UTF-8,舊版本需手動指定編碼轉換
- 異常處理:務必使用 try-with-resources 關閉流,捕獲
IOException
- 並發安全:
Properties 非線程安全,多線程環境需外部同步或使用 ConcurrentHashMap 替代
- 禁用 put/putAll:會導致
store 失敗,堅持使用 setProperty
應用場景
- 應用配置(數據庫連接、路徑、開關)
- 國際化資源包(配合
ResourceBundle)
- 輕量級持久化,避免引入數據庫