在 Java 開發中,java.util.Properties 是一個核心類別,專門用於讀取與管理配置檔案。不同語言有各自支援的配置格式,如 Python 使用 .ini 搭配 ConfigParser,而 Java 則慣用 .properties 文字檔,採「鍵=值」格式,並以 # 表示註解。這種設計讓使用者無需修改程式碼即可調整參數,極大提升了系統的靈活性。
getProperty(String key):依鍵取得對應值load(InputStream inStream):從輸入流載入鍵值對setProperty(String key, String value):設定鍵值對(底層呼叫 Hashtable.put)store(OutputStream out, String comments):將屬性列表寫入輸出流,與 load 互為逆操作clear():清除所有已載入的鍵值對以下提供一套可直接引入專案的 PropertieUtil,涵蓋讀取單一屬性、列印全部內容、寫入屬性三大功能:
package com.javacui.lucene.jdbc;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertieUtil {
private static Logger logger = Logger.getLogger(PropertieUtil.class);
private PropertieUtil() { }
/** 讀取配置檔指定屬性 */
public static String readValue(String filePath, String key) {
Properties props = new Properties();
try {
if (!filePath.startsWith("/")) filePath = "/" + filePath;
InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
return props.getProperty(key);
} catch (Exception e) {
logger.error(e);
return null;
}
}
/** 列印配置檔全部內容 */
public static void readProperties(String filePath) {
Properties props = new Properties();
try {
if (!filePath.startsWith("/")) filePath = "/" + filePath;
InputStream in = PropertieUtil.class.getResourceAsStream(filePath);
props.load(in);
Enumeration<?> en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = props.getProperty(key);
logger.info(key + ":" + value);
}
} catch (Exception e) {
logger.error(e);
}
}
/** 將值寫入配置檔 */
public static void writeProperties(String fileName, String parameterName, String parameterValue) throws Exception {
if (fileName.startsWith("/")) fileName = fileName.substring(1);
String filePath = PropertieUtil.class.getResource("/").getPath() + fileName;
Properties pps = new Properties();
try (InputStream in = new BufferedInputStream(new FileInputStream(filePath));
OutputStream out = new FileOutputStream(filePath)) {
pps.load(in);
pps.setProperty(parameterName, parameterValue);
pps.store(out, "Update " + parameterName + " name");
}
}
public static void main(String[] args) throws Exception {
readProperties("jdbc.properties");
// logger.info(readValue("jdbc.properties", "JAVABLOG_WRITE_URL"));
// writeProperties("test.properties", "test", "test");
}
}
/ 開頭;寫入時則不能帶 /,且需注意 Maven 專案輸出至 target 目錄,非原始碼目錄。Properties.load/store 預設使用 ISO-8859-1,若含中文建議自行處理編碼轉換。掌握 Properties 讀寫技巧,配合封裝良好的工具類,能讓配置管理更輕鬆維護。實務上可再擴充支援多環境配置、熱重載等進階功能。