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

J2SE API 讀取 Properties 檔案六種方式完整比較與最佳實踐

     編輯:J2SE

`Properties` 檔案是 Java 專案常見配置載體。J2SE 提供多種載入路徑:檔案系統、類路徑資源、模組系統等。本文整理六種標準方式並給出測試驗證碼。

六大載入方式

方式API適用場景路徑範例
1. 檔案絕對路徑`Files.newInputStream(Path)`外部化配置、Docker 掛載`/etc/app/config.properties`
2. 類路徑資源`ClassLoader.getResourceAsStream()`打包在 JAR 內的預設配置`com/example/config.properties`
3. 類相對路徑`Class.getResourceAsStream()`同包配置、測試資源`config.properties` (同目錄)
4. ResourceBundle`ResourceBundle.getBundle()`國際化、多環境分層`messages` (基名)
5. PropertyResourceBundle`new PropertyResourceBundle(is)`自定義編碼、非標準載入InputStream 來源
6. Spring @PropertySource`@PropertySource("classpath:...")`Spring 專案統一配置管理SpEL、YAML、加密支援

核心代碼範例

// 方式 2:類路徑(最常用)
try (InputStream is = getClass().getClassLoader()
        .getResourceAsStream("config.properties")) {
    Properties props = new Properties();
    props.load(is); // ISO-8859-1 編碼
    String url = props.getProperty("db.url");
}

// 方式 4:ResourceBundle(支援 Locale 分層)
ResourceBundle rb = ResourceBundle.getBundle("messages", Locale.TRADITIONAL_CHINESE);
String title = rb.getString("helloworld.title");

編碼陷阱與解決

  • `Properties.load(InputStream)` **強制 ISO-8859-1**,中文會亂碼
  • 解法:`load(Reader)` 搭配 `new InputStreamReader(is, StandardCharsets.UTF_8)`
  • 或使用 XML 格式:`loadFromXML(InputStream)` 預設 UTF-8

測試驗證範本

@Test void testAllMethods() {
    String key = "helloworld.title";
    String expected = "Hello World!";
    // 1. 絕對路徑
    assertEquals(expected, loadByAbsolutePath().getProperty(key));
    // 2. 類路徑
    assertEquals(expected, loadByClassLoader().getProperty(key));
    // 3. 類相對路徑
    assertEquals(expected, loadByClassRelative().getProperty(key));
    // 4. ResourceBundle
    assertEquals(expected, ResourceBundle.getBundle("LocalStrings").getString(key));
    // 5. PropertyResourceBundle
    assertEquals(expected, new PropertyResourceBundle(is).getString(key));
    // 6. Spring 環境需整合測試
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved