Properties类用于读取键值对配置文件,继承Hashtable且线程安全。1. 可通过FileInputStream加载文件;2. 推荐使用ClassLoader读取resources目录下的配置文件;3. 常用方法包括load、getProperty、setProperty和store;4. 注意编码问题、流关闭、敏感信息保护及封装为单例提升性能。

在Java中,Properties 类是处理配置文件最常用的方式之一,特别适用于读取以键值对形式存储的 .properties 文件。它继承自 Hashtable,具备线程安全特性,能够方便地从文件、输入流或直接写入数据。
1. Properties类的基本使用
Properties 提供了加载配置文件的核心方法,通常配合 FileInputStream 或 ClassLoader 来读取外部配置文件。
假设项目中有如下 application.properties 文件:
db.url=jdbc:mysql://localhost:3306/mydb db.username=root db.password=123456
可以通过以下代码读取:
立即学习“Java免费学习笔记(深入)”;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties props = new Properties();
try (FileInputStream fis = new FileInputStream("application.properties")) {
props.load(fis); // 加载配置文件
System.out.println("数据库地址: " + props.getProperty("db.url"));
System.out.println("用户名: " + props.getProperty("db.username"));
System.out.println("密码: " + props.getProperty("db.password"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用类路径加载配置文件(推荐方式)
如果配置文件放在 src/main/resources 目录下(Maven/Gradle 项目),建议使用类加载器读取,避免路径硬编码。
例如:将 application.properties 放在 resources 目录下,使用以下方式加载:
Properties props = new Properties();
// 使用类加载器获取资源流
try (var input = ConfigReader.class.getClassLoader()
.getResourceAsStream("application.properties")) {
if (input == null) {
System.out.println("无法找到配置文件!");
return;
}
props.load(input);
System.out.println("加载成功: " + props.getProperty("db.url"));
} catch (IOException e) {
e.printStackTrace();
}
这种方式更灵活,适用于打包成 JAR 后的运行环境。
3. Properties的常用方法说明
- load(InputStream inStream):从输入流加载属性键值对。
- getProperty(String key):根据键获取值,若不存在返回 null。
- getProperty(String key, String defaultValue):获取值,若键不存在则返回默认值。
- setProperty(String key, String value):设置键值对。
- store(OutputStream out, String comment):将属性保存到输出流,可用于写回配置文件。
4. 注意事项与最佳实践
使用 Properties 时需注意以下几点:
- 配置文件默认使用 ISO-8859-1 编码,若含中文需转义或使用 loadFromXML 配合 XML 格式。
- 确保资源流正确关闭,推荐使用 try-with-resources。
- 敏感信息如密码不建议明文存储,生产环境应结合加密或使用专门的配置中心。
- 频繁读取配置可考虑封装为单例工具类,避免重复加载。
基本上就这些。Properties 简单易用,适合中小型项目管理配置,掌握其加载机制和路径处理能有效提升开发效率。










