Java中Properties类是操作.properties配置文件的标准工具,基于线程安全的Hashtable,支持ISO-8859-1编码,默认加载需注意UTF-8乱码问题,推荐从classpath加载,支持动态修改与store/storeToXML保存。

Java 中 Properties 类是操作键值对配置文件(如 .properties 文件)的标准工具,适合处理简单、纯文本的配置场景。它基于 Hashtable,线程安全,天然支持 ISO-8859-1 编码,也兼容 UTF-8(需注意加载方式)。
加载 properties 文件(从 classpath 或文件路径)
推荐优先从 classpath 加载(如放在 src/main/resources 下),便于打包后访问;也可直接读取磁盘路径。
- 从 classpath 加载(推荐):
Properties props = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties")) {
if (is != null) {
props.load(is); // 默认按 ISO-8859-1 解析
}
} catch (IOException e) {
e.printStackTrace();
}
- 从文件系统加载(需指定绝对或相对路径):
try (FileInputStream fis = new FileInputStream("conf/app.properties")) {
props.load(fis);
}
⚠️ 注意:JDK 9+ 支持 UTF-8 编码的 load(Reader) 方法,可避免中文乱码:
try (Reader reader = Files.newBufferedReader(Paths.get("config.properties"), StandardCharsets.UTF_8)) {
props.load(reader);
}
读取属性值(含默认值和类型转换)
Properties 的 getProperty(key) 返回 String,不返回 null(可设默认值);get(key) 是父类 Hashtable 方法,返回 Object,一般不用。
使用ydata-profiling(前身为pandas-profiling)生成全面的数据质量报告,包含相关性分析、缺失值模式和基数检测。导出交互式HTML仪表板和JSON摘要。
立即学习“Java免费学习笔记(深入)”;
- 基础读取(带默认值防空):
String dbUrl = props.getProperty("database.url", "jdbc:h2:mem:test");
String timeout = props.getProperty("connection.timeout", "3000");
- 类型转换需手动(如转 int):
int port = Integer.parseInt(props.getProperty("server.port", "8080"));
建议封装工具方法或使用 Optional 避免 NumberFormatException。
修改并保存 properties 到文件
Properties 对象可动态增删改,但写回文件需显式调用 store() 或 storeToXML()。
- 修改属性(自动覆盖同名 key):
props.setProperty("app.version", "2.1.0");
props.remove("debug.mode");
- 保存为普通 properties 文件(支持注释和时间戳):
try (FileOutputStream fos = new FileOutputStream("config.properties")) {
props.store(fos, "Updated by Java at " + new Date());
}
- 保存为 XML 格式(更规范,天然支持 UTF-8):
try (FileOutputStream fos = new FileOutputStream("config.xml")) {
props.storeToXML(fos, "Config in XML", "UTF-8");
}
注意事项与常见陷阱
实际使用中容易踩坑,尤其涉及编码、路径和线程安全。
- 中文乱码主因是未指定 UTF-8 编码加载/保存,不要依赖 IDE 默认编码
-
getResourceAsStream()返回null表示资源未找到,务必判空,否则抛NullPointerException -
Properties是线程安全的,但批量修改(如循环setProperty)仍建议加锁或用本地副本 - key 中的空格、点、冒号等特殊字符会被解析器转义,写入时尽量用字母数字下划线命名
- Spring Boot 等框架已封装更强大的配置管理(如
@Value、@ConfigurationProperties),简单项目用Properties足够,复杂场景建议升级

















