Java 標準庫提供多種讀取 .properties 設定檔的方式,各有適用場景:
Properties.load() + FileInputStreamInputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
Properties props = new Properties();
props.load(in);
最直接的方式,適用於檔案系統路徑(絕對或相對)。打包成 JAR 後無法存取 JAR 內資源。
ResourceBundle.getBundle()ResourceBundle rb = ResourceBundle.getBundle("config", Locale.getDefault());
從 Classpath 載入 config.properties(無副檔名),內建 Locale 解析與快取,適合國際化資源。僅支援 String 鍵值。
PropertyResourceBundle 建構子InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
ResourceBundle rb = new PropertyResourceBundle(in);
手動建立 ResourceBundle 實例,可載入任意路徑檔案,結合 ResourceBundle API 優勢。
Class.getResourceAsStream()InputStream in = MyClass.class.getResourceAsStream("/config.properties");
Properties props = new Properties();
props.load(in);
相對於該類別所在包的路徑(以 / 開頭表示 Classpath 根目錄)。適合模組內部資源。
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);
使用系統類別載入器,載入應用層級 Classpath 資源。
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 才能生效。/,勿用系統相關分隔符。