在 Java 開發中,.properties 配置文件廣泛用於存儲鍵值對配置。本文系統梳理了 7 種讀取屬性文件的方法,涵蓋標準庫與第三方庫,幫助開發者根據場景選擇最適合的方案。
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
Properties props = new Properties();
props.load(in);
String value = props.getProperty("key");
適用於文件系統絕對/相對路徑讀取,需手動關閉流。
ResourceBundle bundle = ResourceBundle.getBundle("config", Locale.getDefault());
String value = bundle.getString("key");
基於類路徑,自動按 Locale 匹配 config_zh_CN.properties 等變體,適合國際化場景。
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
ResourceBundle bundle = new PropertyResourceBundle(in);
本質上同方式二,但允許直接傳入 InputStream,靈活性稍高。
InputStream in = MyClass.class.getResourceAsStream("/config.properties");
Properties props = new Properties();
props.load(in);
相對當前類的包路徑,/ 表示 classpath 根目錄,打包成 JAR 後依然有效。
InputStream in = MyClass.class.getClassLoader().getResourceAsStream("config.properties");
Properties props = new Properties();
props.load(in);
統一從 classpath 根目錄查找,避免包路徑困擾,是框架開發常用姿勢。
InputStream in = ClassLoader.getSystemResourceAsStream("config.properties");
Properties props = new Properties();
props.load(in);
委派給系統類加載器,適用於啟動類路徑下的資源。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.10.1</version>
</dependency>
Configuration config = new PropertiesConfiguration("config.properties");
String value = config.getProperty("key");
支援自動重載、類型轉換、表達式插值等高級特性,適合複雜配置管理需求。
| 場景 | 推薦方式 |
|---|---|
| 簡單獨立應用 | 方式一、四、五 |
| 國際化多語言 | 方式二 |
| Spring/框架整合 | 方式五 + @PropertySource |
| 熱加載/高級功能 | 方式七 |
最佳實踐:優先使用 ClassLoader.getResourceAsStream 確保打包後路徑正確;生產環境建議配合 try-with-resources 自動關閉流,並處理 null 防 NPE。