Properties.load(InputStream) 使用 ISO-8859-1 解碼,中文會亂碼;Properties.load(Reader) 使用文件實際編碼(如 UTF-8),完美支持中文鍵值。
Properties props = new Properties();
try (FileReader reader = new FileReader("config.properties")) { // 自動用默認編碼
props.load(reader);
// 遍歷所有鍵值
props.stringPropertyNames().forEach(key ->
System.out.println(key + "=" + props.getProperty(key)));
} catch (IOException e) {
e.printStackTrace();
}
# config.properties # 空格、冒號、等號需轉義 user\ name = zhangsan password = 123456 chinese\ key = 中文值 url = jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
:、= 時前加 \ 轉義。// 錯誤示範:中文鍵值讀出為亂碼
try (InputStream in = new BufferedInputStream(new FileInputStream("config.properties"))) {
props.load(in); // ISO-8859-1 解碼
System.out.println(props.getProperty("chinese\ key")); // 亂碼
}
// application-dev.properties
db.url=jdbc:mysql://dev:3306/app
// application-prod.properties
db.url=jdbc:mysql://prod:3306/app
// 代碼中根據啟動參數動態加載
String env = System.getProperty("env", "dev");
try (FileReader r = new FileReader("application-" + env + ".properties")) {
props.load(r);
}
FileReader / InputStreamReader(StandardCharsets.UTF_8)。File Encodings → UTF-8。@ConfigurationProperties (Spring Boot) 或 Apache Commons Configuration 實現類型安全綁定與熱加載。