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

Java 讀取 Properties 設定檔六大標準技巧總覽

     編輯:J2SE

六種核心方法一覽

Java 標準庫提供多種讀取 .properties 設定檔的方式,各有適用場景:

1. 經典 Properties.load() + FileInputStream

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

最直接的方式,適用於檔案系統路徑(絕對或相對)。打包成 JAR 後無法存取 JAR 內資源。

2. ResourceBundle.getBundle()

ResourceBundle rb = ResourceBundle.getBundle("config", Locale.getDefault());

從 Classpath 載入 config.properties(無副檔名),內建 Locale 解析與快取,適合國際化資源。僅支援 String 鍵值。

3. PropertyResourceBundle 建構子

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

手動建立 ResourceBundle 實例,可載入任意路徑檔案,結合 ResourceBundle API 優勢。

4. Class.getResourceAsStream()

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

相對於該類別所在包的路徑(以 / 開頭表示 Classpath 根目錄)。適合模組內部資源。

5. ClassLoader.getResourceAsStream()

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

相對於 Classpath 根目錄,跨模組共享資源的常用方式。

6. ClassLoader.getSystemResourceAsStream()

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

使用系統類別載入器,載入應用層級 Classpath 資源。

補充:Servlet 環境專用

InputStream in = context.getResourceAsStream("/WEB-INF/config.properties");
Properties props = new Properties();
props.load(in);

在 Web 容器中必須使用 ServletContext 以正確解析 WAR 結構路徑。

快速選擇指南

需求推薦方法關鍵限制
檔案在專案外、需執行期修改方法 1 (FileInputStream)JAR 部署失效
國際化、多語系、唯讀方法 2 (ResourceBundle)僅 String、快取難刷新
JAR 內資源、模組內部方法 4 (Class.getResourceAsStream)路徑相對於類別包
共享資源、跨模組方法 5 (ClassLoader.getResourceAsStream)路徑相對 Classpath 根
Web 應用部署ServletContext.getResourceAsStream需 ServletContext

避坑提醒

  • 所有 InputStream 用畢必須 close(),建議使用 try-with-resources。
  • ResourceBundle 預設快取,修改檔案需重啟或自訂 ResourceBundle.Control 才能生效。
  • 路徑分隔符:Classpath 統一用 /,勿用系統相關分隔符。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved