Java 標準配置:Properties (key=value) 、XML (結構化)。但 INI 格式具備:
[Section]) 邏輯分組; comment) 可讀性佳JDK 無內建 INI 解析器,本文提供純 Java 實作 (無 JNI/外部依賴)。
; 全域註解
[Database] ; 區段標題
host=localhost ; 鍵值對
port=3306
; 區段內註解
username=root
password=secret
[Logging]
level=DEBUG
file=app.log
public final class ConfigurationFile {
// 讀取單一值
public static String getProfileString(String file, String section,
String variable, String defaultValue)
throws IOException { ... }
// 修改單一值 (保留註解、格式)
public static boolean setProfileString(String file, String section,
String variable, String value)
throws IOException { ... }
}
Pattern sectionPattern = Pattern.compile("^\\s*\\[\\s*(.+?)\\s*\\]\\s*$");
^\s*\[:行首可有空白,接 [\s*(.+?)\s*:非貪婪捕獲區段名\]\s*$:接 ] 到行尾// 移除行內註解
String line = rawLine.split(";")[0].trim();
// 分割鍵值 (僅第一個 =)
String[] kv = line.split("=", 2);
String key = kv[0].trim();
String val = kv.length > 1 ? kv[1].trim() : "";
BufferedReader 逐行讀取isInTargetSection 狀態defaultValueStringBuilder fileContentkey = newValue ; 原註解BufferedWriter 覆寫原檔案
public static String getProfileString(String file, String section, String key, String def) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inSection = false;
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
String content = line.split(";")[0]; // 去註解
// 區段判斷
Matcher m = Pattern.compile("^\\[\\s*(.+?)\\s*\\]$").matcher(content);
if (m.matches()) {
inSection = m.group(1).equalsIgnoreCase(section);
continue;
}
if (inSection) {
String[] kv = content.split("=", 2);
if (kv[0].trim().equalsIgnoreCase(key)) {
return kv.length > 1 ? kv[1].trim() : "";
}
}
}
}
return def;
}
public static boolean setProfileString(String file, String section, String key, String value) throws IOException {
List lines = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);
boolean inSection = false;
boolean found = false;
for (int i = 0; i < lines.size(); i++) {
String raw = lines.get(i);
String content = raw.split(";")[0].trim();
String comment = raw.contains(";") ? ";" + raw.split(";")[1] : "";
Matcher m = Pattern.compile("^\\[\\s*(.+?)\\s*\\]$").matcher(content);
if (m.matches()) {
inSection = m.group(1).equalsIgnoreCase(section);
continue;
}
if (inSection && !found) {
String[] kv = content.split("=", 2);
if (kv[0].trim().equalsIgnoreCase(key)) {
lines.set(i, kv[0].trim() + " = " + value + " " + comment);
found = true;
}
}
}
if (found) Files.write(Paths.get(file), lines, StandardCharsets.UTF_8);
return found;
}
// config.ini
[Settings]
SampSize=100
; 取樣率
public static void main(String[] args) throws IOException {
System.out.println(getProfileString("config.ini", "Settings", "SampSize", "0")); // 100
setProfileString("config.ini", "Settings", "SampSize", "200");
System.out.println(getProfileString("config.ini", "Settings", "SampSize", "0")); // 200
}
# 註解\)getInt(), getBoolean(), getList()| 庫 | 特色 | Maven 坐標 |
|---|---|---|
| Apache Commons Configuration | 支援 INI、XML、Properties、JNDI、資料庫等多源、統一 API | commons-configuration:commons-configuration |
| ini4j | 專精 INI 格式、支援 Windows Registry 風格 | org.ini4j:ini4j |
| Typesafe Config (HOCON) | JSON 超集、支援 include、變數替換、Akka/Play 專用 | com.typesafe:config |