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

Java 讀取配置檔案實戰:Properties 類別與類別路徑資源載入完整指南

     編輯:Java 程式設計入門

前言

配置檔案分離是軟體工程基本原則。Java java.util.Properties 類別提供鍵值對持久化支援,配合 Class.getResourceAsStream() 可實現獨立於檔案系統路徑的資源載入。本文以實戰代碼示範標準讀取模式、異常處理與資源釋放最佳實務。

核心代碼實現

package net.jspcn.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigReader {

    /**
     * 從類別路徑讀取屬性檔並取得指定鍵值
     * @param fileName 資源路徑(相對類別路徑),如 "db.properties"
     * @return 指定鍵對應的值,若不存在回傳 null
     */
    public String getProperty(String fileName, String key) {
        Properties props = new Properties();
        
        // 使用類別載入器取得資源流,支援 JAR 內資源讀取
        try (InputStream is = getClass().getResourceAsStream(fileName)) {
            if (is == null) {
                System.err.println("找不到配置資源: " + fileName);
                return null;
            }
            props.load(is);
            // InputStream 由 try-with-resources 自動關閉
        } catch (IOException e) {
            System.err.println("讀取配置檔失敗 [" + fileName + "]: " + e.getMessage());
            // 生產環境建議使用日誌框架記錄
            // log.error("配置載入失敗", e);
        }
        
        return props.getProperty(key);
    }

    // 測試主程式
    public static void main(String[] args) {
        ConfigReader reader = new ConfigReader();
        String fileName = reader.getProperty("db.properties", "file_name");
        System.out.println("讀取結果: " + fileName);
    }
}

關鍵技術點解析

1. getResourceAsStream() vs FileInputStream

方式適用場景優點缺點
Class.getResourceAsStream()類別路徑資源(src/main/resources、JAR 內檔案)獨立於作業系統路徑、支援 JAR 打包、單元測試友善唯讀,無法寫入
new FileInputStream()外部配置檔(/etc/app/config.properties)可讀寫、絕對路徑控制路徑耦合部署環境、Docker/K8s 需掛載卷

2. 資源路徑解析規則

  • 以 / 開頭:從類別路徑根目錄查找(/config/db.properties)
  • 不以 / 開頭:從當前類別所在套件目錄查找(net/jspcn/test/db.properties)
  • 建議統一使用絕對路徑:getClass().getResourceAsStream("/db.properties")

3. Properties 進階用法

// 載入多個配置檔,後載入覆蓋先載入
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/default.properties"));
props.load(getClass().getResourceAsStream("/env.properties"));

// 取得值並提供預設值(Java 8+)
String url = props.getProperty("db.url", "jdbc:mysql://localhost:3306/default");

// 型別轉換輔助
int port = Integer.parseInt(props.getProperty("db.port", "3306"));
boolean ssl = Boolean.parseBoolean(props.getProperty("db.ssl", "false"));

// 遍歷所有屬性
props.forEach((k, v) -> System.out.println(k + " = " + v));

配置檔範例 (db.properties)

# 資料庫連線配置
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/myapp?useSSL=false&serverTimezone=UTC
db.username=app_user
db.password=secret123
db.pool.size=20

# 應用參數
file_name=WinRAR.exe
app.mode=production

現代化替代方案

💡 企業級專案建議
  • Spring Boot:@ConfigurationProperties + application.yml,支援類型安全綁定、Profile 環境隔離、配置熱更新
  • Apache Commons Configuration:支援 XML、JSON、INI、資料庫等多種來源,提供配置合併、重載監聽
  • MicroProfile Config / Spring Cloud Config:雲原生環境下的分散式配置中心整合

常見問題排查

現象可能原因解決方案
回傳 null / 找不到資源檔案未放入類別路徑、路徑大小寫錯誤、打包時未包含 resources檢查 target/classes 或 JAR 內結構;Maven 專案確認 src/main/resources 配置
中文亂碼Properties 預設 ISO-8859-1 編碼檔案存為 UTF-8,讀取時用 new InputStreamReader(is, StandardCharsets.UTF_8) 包裝
修改配置需重啟Properties 無熱更新機制引入 Spring Cloud Config、Apollo 或自訂 WatchService 監聽檔案變更

總結

Properties + getResourceAsStream() 是 Java 輕量級配置讀取的經典組合。掌握類別路徑資源載入機制、try-with-resources 資源管理、編碼處理,能解決 80% 的配置讀取需求。複雜場景建議升級成熟配置框架,獲得類型安全、熱更新、分散式管理等進階能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved