










在 Java 编程中,java.util.Properties 是一个专门用于处理键值对配置文件的类,它继承自 Hashtable<Object,Object>,但强制要求键值对均为字符串类型(实际是 Hashtable<String,String>)。以下是其核心特性和使用场景:
键值对存储
key=value 格式存储数据(类似 .ini 或 .properties 文件)user.name=John,database.port=3306文件 IO 支持
load() 方法从输入流(如文件、网络资源)加载配置store() 方法将配置持久化到文件// 加载配置文件
try (InputStream input = new FileInputStream("config.properties")) {
Properties prop = new Properties();
prop.load(input);
}
// 保存配置文件
try (OutputStream output = new FileOutputStream("config.properties")) {
prop.store(output, "Database configuration");
}
编码处理
load(Reader)/store(Writer) 方法指定编码:prop.load(new InputStreamReader(input, "UTF-8"));
层次化访问
Properties 对象链式继承(defaults 属性)Properties defaults = new Properties();
defaults.setProperty("timeout", "30");
Properties prop = new Properties(defaults); // 继承默认值
配置文件管理
config.properties:# Database settings
db.url=jdbc:mysql://localhost:3306/mydb
db.user=root
db.password=secret
国际化支持
messages_en.properties、messages_zh.properties)系统属性扩展
System.getProperties() 配合使用,扩展 JVM 参数线程安全
Hashtable,Properties 是线程安全的,但频繁同步可能影响性能资源释放
InputStream/OutputStream(推荐 try-with-resources)类型局限
int timeout = Integer.parseInt(prop.getProperty("timeout"));
替代方案
// 读取配置
Properties prop = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream("app.properties")) {
prop.load(input);
String dbUrl = prop.getProperty("db.url");
String dbUser = prop.getProperty("db.user", "admin"); // 带默认值
} catch (IOException ex) {
ex.printStackTrace();
}
// 动态修改配置
prop.setProperty("cache.enabled", "true");
try (OutputStream output = new FileOutputStream("app.properties")) {
prop.store(output, "Updated cache settings");
}
| 场景 | 推荐工具 | 优势 |
|---|---|---|
| 复杂层级配置 | Apache Commons Configuration | 支持 XML、JSON、INI 等多种格式 |
| 云原生配置 | Spring Cloud Config | 集中化管理,动态刷新 |
| 高性能键值存储 | Redis | 内存数据库,支持分布式 |
Properties 是 Java 生态中轻量级配置管理的基石,适合简单场景,但在复杂工程中建议结合具体需求选择更专业的配置管理方案。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。