java.util.Properties 繼承自 Hashtable<Object, Object>,專門用於鍵值對配置存儲,支持 key=value、key:value、key value 三種格式,默認編碼 ISO-8859-1(需注意中文處理)。
| 方法 | 說明 |
|---|---|
load(InputStream) | 從字節流加載(ISO-8859-1 編碼) |
load(Reader) | 從字符流加載(可指定編碼,推薦) |
store(OutputStream, comments) | 寫入字節流 |
store(Writer, comments) | 寫入字符流(可指定編碼) |
getProperty(key) | 獲取值,不存在返回 null |
getProperty(key, defaultValue) | 獲取值,不存在返回默認值 |
setProperty(key, value) | 設置屬性(自動轉字符串) |
public Properties loadFromClasspath(String path) {
Properties props = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(path)) {
if (is == null) {
throw new IllegalArgumentException("配置文件不存在: " + path);
}
// 方式一:JDK 9+ 直接用 Reader 指定 UTF-8
try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
props.load(reader);
}
// 方式二:舊版本需手動轉碼
// props.load(new InputStreamReader(is, "UTF-8"));
} catch (IOException e) {
throw new RuntimeException("加載配置失敗: " + path, e);
}
return props;
}
public Properties loadFromFile(String filePath) {
Properties props = new Properties();
try (Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)) {
props.load(reader);
} catch (IOException e) {
throw new RuntimeException("讀取文件失敗: " + filePath, e);
}
return props;
}
@Configuration
@PropertySource(value = "classpath:app.properties", encoding = "UTF-8")
public class AppConfig {
@Autowired
private Environment env;
public String getValue(String key) {
return env.getProperty(key);
}
}
Properties 歷史包袱:load(InputStream) 強制 ISO-8859-1。三種解決路徑:
props.load(new InputStreamReader(is, StandardCharsets.UTF_8))new String(value.getBytes("ISO-8859-1"), "UTF-8")application.yml,原生支持 UTF-8、層級結構、類型安全public void updateProperty(String filePath, String key, String value) {
Properties props = loadFromFile(filePath);
props.setProperty(key, value);
try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) {
props.store(writer, "Updated by application at " + LocalDateTime.now());
} catch (IOException e) {
throw new RuntimeException("寫入配置失敗", e);
}
}
@RefreshScope、Apollo/Nacos 等配置中心| 現象 | 原因 | 修正 |
|---|---|---|
| 中文讀取亂碼 | 用 load(InputStream) 讀取 UTF-8 文件 | 改用 load(Reader) 指定 UTF-8 |
| 寫入後中文變 Unicode 轉義 | store 默認輸出 ASCII 轉義 | 用 store(Writer, UTF-8) 寫入 |
| 修改不生效 | 只修改內存對象,未 store 回文件 | 調用 store 寫入磁盤 |
| 多線程並發修改丟失 | Properties 非線程安全 | 加鎖或用 ConcurrentHashMap 替代 |