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

Java 讀取 Properties 配置文件的 6 種方式全解析與最佳實踐

     編輯:Java 相關知識

常見配置文件場景

  • config.properties:系統常量、版本號、路徑
  • database.properties:數據庫連接參數
  • log4j.properties:日誌配置
  • redis.properties:緩存配置

格式:key=value,註釋用 #。

Properties 類讀取(4 種方式)

// 方式一:文件絕對路徑
InputStream in = new BufferedInputStream(new FileInputStream("文件路徑"));
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("version"));

// 方式二:類路徑相對路徑(同包下)
InputStream in = PropertiesUtil.class.getResourceAsStream("文件名");
Properties p = new Properties();
p.load(in);

// 方式三:類路徑絕對路徑(從 classpath 根)
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("文件名");
Properties p = new Properties();
p.load(in);

// 方式四:系統類加載器
InputStream in = ClassLoader.getSystemResourceAsStream("文件名");
Properties p = new Properties();
p.load(in);

區別總結

方式適用場景路徑前綴
FileInputStream文件系統絕對/相對路徑文件系統路徑
getResourceAsStream同包資源相對當前類包
getClassLoader().getResourceAsStreamclasspath 根資源/ 即 classpath 根
ClassLoader.getSystemResourceAsStream系統類加載器可見資源/ 即 classpath 根

ResourceBundle 讀取(2 種方式)

專為國際化設計,支持 基名_語言_國家.properties 命名規範。

// 方式五:默認 Locale
ResourceBundle rb = ResourceBundle.getBundle("文件名前綴", Locale.getDefault());
System.out.println(rb.getObject("version"));

// 方式六:自定義輸入流
InputStream is = new BufferedInputStream(new FileInputStream("文件路徑"));
ResourceBundle rb = new PropertyResourceBundle(is);
System.out.println(rb.getObject("version"));

⚠️ 關鍵限制:緩存機制

ResourceBundle 首次讀取後永久緩存,修改配置文件需重啟 JVM 才能生成效,不適合熱更新場景。

最佳實踐建議

  1. 通用配置:優先使用 Properties + getClassLoader().getResourceAsStream(),支持 classpath 熱加載(配合監聽器)
  2. 國際化資源:使用 ResourceBundle,利用其 Locale 解析機制
  3. Spring 環境:直接用 @PropertySource + @Value 或 Environment,框架級支持熱刷新
  4. 避免硬編碼路徑:統一放置於 src/main/resources 或 config 目錄

進階:封裝通用工具類

public class PropsUtil {
    public static Properties load(String classpath) {
        Properties props = new Properties();
        try (InputStream is = Thread.currentThread()
                .getContextClassLoader().getResourceAsStream(classpath)) {
            if (is != null) props.load(is);
        } catch (IOException e) {
            throw new RuntimeException("載入配置失敗: " + classpath, e);
        }
        return props;
    }
    
    public static String get(Properties props, String key, String def) {
        return props.getProperty(key, def);
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved