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

Java 讀取屬性檔的 7 種方式完整指南:從標準 API 到第三方庫

     編輯:Java 程式設計入門

前言:為什麼需要多種讀取方式?

Java 應用中屬性檔的讀取場景多樣:classpath 內嵌配置、外部檔案系統配置、Spring 環境整合、多環境隔離等。不同場景下最佳讀取方式不同,本文系統梳理 7 種主流方式,並給出選型建議。

方式一:Properties + FileInputStream(檔案系統絕對路徑)

Properties props = new Properties();
try (InputStream in = new BufferedInputStream(new FileInputStream("/opt/config/app.properties"))) {
    props.load(in);
}
String value = props.getProperty("key");
  • 適用:外部化配置檔案,路徑固定
  • 缺點:硬編碼路徑,跨平台部署麻煩

方式二:ResourceBundle(標準國際化資源包)

// 僅支援 classpath 下的 .properties 檔,檔名不含副檔名
ResourceBundle bundle = ResourceBundle.getBundle("config.app", Locale.getDefault());
String value = bundle.getString("key");
  • 適用:國際化訊息、靜態資源包
  • 限制:只能讀取 classpath、快取機制導致熱更新困難、不支援任意路徑

方式三:PropertyResourceBundle(底層實現)

try (InputStream in = new BufferedInputStream(new FileInputStream("app.properties"))) {
    ResourceBundle bundle = new PropertyResourceBundle(in);
    String value = bundle.getString("key");
}
  • 本質同方式二,手動控制輸入流來源

方式四:Class.getResourceAsStream(相對類路徑)

// 相對當前類所在包路徑
try (InputStream in = MyClass.class.getResourceAsStream("config.properties")) {
    Properties props = new Properties();
    props.load(in);
}
  • 路徑規則:不以 / 開頭 = 相對當前類包路徑;以 / 開頭 = 相對 classpath 根目錄

方式五:ClassLoader.getResourceAsStream(Classpath 根路徑)

// 推薦:統一從 classpath 根目錄讀取
try (InputStream in = MyClass.class.getClassLoader().getResourceAsStream("config/app.properties")) {
    Properties props = new Properties();
    props.load(in);
}
  • 最常用:Spring Boot、Maven 標準目錄結構下首選
  • 不支援相對路徑,永遠從 classpath 根開始

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

try (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>

// 程式碼
PropertiesConfiguration config = new PropertiesConfiguration("test.properties");
String value = config.getProperty("key").toString();
  • 優勢:支援自動重載、變數插值、多檔案合併、類型轉換、XML/YAML 等多格式
  • 適用:複雜配置管理、熱更新需求、微服務配置中心客戶端

選型決策表

最佳實踐封裝範例

public final class PropUtils {
    private PropUtils() {}
    
    public static Properties loadFromClasspath(String path) {
        Properties props = new Properties();
        try (InputStream in = PropUtils.class.getClassLoader().getResourceAsStream(path)) {
            if (in == null) throw new IllegalArgumentException("找不到資源: " + path);
            props.load(in);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        return props;
    }
    
    public static Properties loadFromFileSystem(String absolutePath) {
        Properties props = new Properties();
        try (InputStream in = new FileInputStream(absolutePath)) {
            props.load(in);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        return props;
    }
}

總結

理解各種讀取方式的底層機制與適用邊界,能讓你在不同架構下做出正確選擇。現代 Spring Boot 專案建議優先使用框架原生配置綁定機制;獨立應用或工具類庫則以 ClassLoader.getResourceAsStream 為基準,按需引入 Commons Configuration 處理進階需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
場景推薦方式理由
Spring Boot 專案@Value / @ConfigurationProperties框架原生支援,自動綁定、驗證、熱更新
獨立 Java 應用,配置在 classpath方式五標準、無依賴、路徑穩定
配置檔在檔案系統外部方式一 + 路徑參數化支援外掛式部署
國際化訊息方式二JDK 內建、Locale 整合
需熱更新、複雜類型、多源合併方式七功能最完整