java如何使用properties
使用 Properties 类加载和读取配置文件
在 Java 中,java.util.Properties 类用于处理键值对格式的配置文件(通常以 .properties 为后缀)。以下是基本使用方法:
创建 Properties 对象并加载文件
Properties prop = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
读取属性值
String username = prop.getProperty("username");
String password = prop.getProperty("password", "defaultPassword"); // 带默认值
通过类加载器读取资源文件
当配置文件位于类路径(如 resources 目录)时,可以通过类加载器获取:
try (InputStream input = getClass().getClassLoader().getResourceAsStream("app.properties")) {
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
写入 Properties 文件
将属性写入文件:
try (OutputStream output = new FileOutputStream("config.properties")) {
prop.setProperty("db.url", "jdbc:mysql://localhost:3306/mydb");
prop.store(output, "Database configuration");
} catch (IOException io) {
io.printStackTrace();
}
处理中文编码
Properties 文件默认使用 ISO-8859-1 编码。如需处理中文,可使用 ResourceBundle 或转换为 Unicode 转义序列:
// 使用 ResourceBundle 读取中文(文件需为 UTF-8)
ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control());
String value = bundle.getString("key");
// 自定义 UTF8Control 类需继承 ResourceBundle.Control
与 XML 格式交互
Properties 支持 XML 格式的读写:
// 从 XML 加载
prop.loadFromXML(new FileInputStream("config.xml"));
// 保存为 XML
prop.storeToXML(new FileOutputStream("config.xml"), "XML配置");
默认值链
通过继承实现默认值覆盖:

Properties defaults = new Properties();
defaults.setProperty("color", "red");
Properties props = new Properties(defaults);
String color = props.getProperty("color"); // 返回 "red"
注意事项
- 文件路径区分绝对路径和类路径资源
- 修改后的 Properties 需要显式调用
store()保存 - 生产环境建议使用配置管理工具(如 Spring Boot 的
@ConfigurationProperties)






