Properties类用于读写.properties配置文件,支持键值对存储,常用load()读取、store()写入,适合Java项目配置管理。

在Java开发中,Properties 类是处理配置文件最常用的方式之一。它继承自 Hashtable,专门用于读取和保存键值对形式的配置信息,通常配合 .properties 文件使用。这类文件常用于存储数据库连接、应用参数、国际化资源等。
读取配置文件
使用 Properties 读取配置文件是其最常见的用途。一般通过 load() 方法从输入流加载属性。
假设项目根目录下有一个名为 config.properties 的文件,内容如下:
app.name=MyApplication app.version=1.0.0 db.url=jdbc:mysql://localhost:3306/test db.user=root db.password=123456
可以通过以下代码读取这些配置:
立即学习“Java免费学习笔记(深入)”;
- 创建 Properties 对象
- 使用类加载器或 FileInputStream 加载文件
- 调用 load() 方法解析内容
- 通过 getProperty() 获取指定键的值
示例代码:
import java.io.*;
import java.util.Properties;
public class ReadConfig {
public static void main(String[] args) {
Properties prop = new Properties();
try (InputStream input = ReadConfig.class.getClassLoader().getResourceAsStream("config.properties")) {
if (input == null) {
System.out.println("无法找到配置文件");
return;
}
prop.load(input);
System.out.println("应用名称: " + prop.getProperty("app.name"));
System.out.println("数据库URL: " + prop.getProperty("db.url"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
注意:使用 getClassLoader().getResourceAsStream() 可以从类路径下加载文件,适用于打包成 JAR 后的场景。
保存配置到文件
除了读取,Properties 还支持将当前属性写入文件,使用 store() 方法即可。
这在运行时需要动态修改配置并持久化时非常有用。
示例:创建一个新的配置并保存到本地文件
import java.io.*;
import java.util.Properties;
public class SaveConfig {
public static void main(String[] args) {
Properties prop = new Properties();
prop.setProperty("server.host", "192.168.1.100");
prop.setProperty("server.port", "8080");
prop.setProperty("debug", "true");
try (OutputStream output = new FileOutputStream("output-config.properties")) {
prop.store(output, "Generated configuration file");
System.out.println("配置已保存");
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行后会生成 output-config.properties 文件,内容包含键值对及你指定的注释。
加载本地文件而非类路径资源
如果配置文件不在类路径中,而是放在某个具体路径(如项目外部),可以使用 FileInputStream 直接读取。
例如读取项目根目录下的 config.properties:
try (FileInputStream fis = new FileInputStream("config.properties")) {
prop.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
这种方式适合需要用户自定义配置文件路径的场景。
注意事项与建议
使用 Properties 时有几个关键点需要注意:
- .properties 文件默认采用 ISO-8859-1 编码,若需中文,应使用 Unicode 转义(如\u4E2D)或改用 load(new InputStreamReader(..., "UTF-8"))
- getProperty(key) 返回 null 表示键不存在,建议提供默认值:getProperty(key, defaultValue)
- store() 方法生成的文件会包含时间戳,若不需要可自行格式化输出
- 敏感信息如密码不建议明文存储在 .properties 中,生产环境应加密或使用安全配置中心
基本上就这些。Properties 简单易用,适合中小型项目的配置管理,掌握它的读写操作对日常开发很有帮助。










