配置檔案分離是軟體工程基本原則。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);
}
}
| 方式 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
Class.getResourceAsStream() | 類別路徑資源(src/main/resources、JAR 內檔案) | 獨立於作業系統路徑、支援 JAR 打包、單元測試友善 | 唯讀,無法寫入 |
new FileInputStream() | 外部配置檔(/etc/app/config.properties) | 可讀寫、絕對路徑控制 | 路徑耦合部署環境、Docker/K8s 需掛載卷 |
/ 開頭:從類別路徑根目錄查找(/config/db.properties)/ 開頭:從當前類別所在套件目錄查找(net/jspcn/test/db.properties)getClass().getResourceAsStream("/db.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.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
@ConfigurationProperties + application.yml,支援類型安全綁定、Profile 環境隔離、配置熱更新| 現象 | 可能原因 | 解決方案 |
|---|---|---|
| 回傳 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% 的配置讀取需求。複雜場景建議升級成熟配置框架,獲得類型安全、熱更新、分散式管理等進階能力。