Java 應用程式常透過 .properties 檔案外部化配置(資料庫連線、系統參數等)。本文示範標準 java.util.Properties API 載入、讀取、寫入與路徑解析的完整範例,並說明相對路徑陷阱與最佳實踐。
jdbc.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc.url=jdbc:microsoft:sqlserver://10.0.0.168:1433;
jdbc.username=sa
jdbc.password=sa
jndi.databaseName=northwind
package zy.pro.wd.demo;
import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesDemo {
public void testPropertiesFile() {
try {
Properties props = new Properties();
// 載入配置檔
props.load(new FileInputStream("src/jdbc.properties"));
// 讀取屬性
System.out.println(props.getProperty("jdbc.driver"));
System.out.println(props.getProperty("jdbc.url"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PropertiesDemo().testPropertiesFile();
}
}
| 方法 | 用途 |
|---|---|
load(InputStream) | 從輸入流載入鍵值對(ISO 8859-1 編碼) |
load(Reader) | 從字元流載入(支援 UTF-8 等編碼,Java 1.6+) |
getProperty(String key) | 取得屬性值,鍵不存在回傳 null |
getProperty(String key, String defaultValue) | 指定預設值,避免 null 判斷 |
setProperty(String key, String value) | 設定屬性(僅影響記憶體中物件) |
store(OutputStream, String comments) | 寫回檔案,附註釋 |
new FileInputStream("src/jdbc.properties") 的相對基準是程式啟動的工作目錄,非專案根目錄。常見情境:
src/... 正確。src/。// 相對於 classpath 根目錄(src 編譯後輸出位置)
InputStream is = PropertiesDemo.class.getResourceAsStream("/jdbc.properties");
// 或
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
props.load(is);
jdbc.properties 放入 src/(Maven 則為 src/main/resources),編譯後自動複製到 classes/ 根目錄。public void saveConfig(String filename, Properties props) {
try (FileOutputStream fos = new FileOutputStream(filename)) {
props.setProperty("last.update", new java.util.Date().toString());
props.store(fos, "Application Configuration - Auto Generated");
} catch (IOException e) {
e.printStackTrace();
}
}
com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc:microsoft:sqlserver://10.0.0.168:1433;
環境:Eclipse 3.0 測試通過。
掌握 Properties 載入/存取核心 API,並改用 Class.getResourceAsStream() 透過類別路徑存取配置檔,是 Java 應用從開發到部署各環境通用的穩健做法。避免硬編碼相對路徑,讓配置真正外部化、可維護。