首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀取屬性文件的 7 種常用方式總結

     編輯:Java 相關知識

在 Java 開發中,.properties 配置文件廣泛用於存儲鍵值對配置。本文系統梳理了 7 種讀取屬性文件的方法,涵蓋標準庫與第三方庫,幫助開發者根據場景選擇最適合的方案。

方式一:Properties + FileInputStream(基礎用法)

InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
Properties props = new Properties();
props.load(in);
String value = props.getProperty("key");

適用於文件系統絕對/相對路徑讀取,需手動關閉流。

方式二:ResourceBundle(國際化首選)

ResourceBundle bundle = ResourceBundle.getBundle("config", Locale.getDefault());
String value = bundle.getString("key");

基於類路徑,自動按 Locale 匹配 config_zh_CN.properties 等變體,適合國際化場景。

方式三:PropertyResourceBundle(底層實現)

InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
ResourceBundle bundle = new PropertyResourceBundle(in);

本質上同方式二,但允許直接傳入 InputStream,靈活性稍高。

方式四:Class.getResourceAsStream(類路徑讀取)

InputStream in = MyClass.class.getResourceAsStream("/config.properties");
Properties props = new Properties();
props.load(in);

相對當前類的包路徑,/ 表示 classpath 根目錄,打包成 JAR 後依然有效。

方式五:ClassLoader.getResourceAsStream(推薦用法)

InputStream in = MyClass.class.getClassLoader().getResourceAsStream("config.properties");
Properties props = new Properties();
props.load(in);

統一從 classpath 根目錄查找,避免包路徑困擾,是框架開發常用姿勢。

方式六:ClassLoader.getSystemResourceAsStream(系統類加載器)

InputStream in = ClassLoader.getSystemResourceAsStream("config.properties");
Properties props = new Properties();
props.load(in);

委派給系統類加載器,適用於啟動類路徑下的資源。

方式七:Apache Commons Configuration(功能最豐富)

<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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved