Java的Properties类用于读取.properties配置文件,继承自Hashtable,支持键值对存储。1. 在src/main/resources下创建config.properties文件,包含数据库和应用配置。2. 使用ClassLoader获取资源流,通过load()方法加载配置,推荐类路径方式确保打包后可访问。3. 常用方法:getProperty()获取值,可设默认值;setProperty()设置新属性;store()保存修改。4. 注意文件位置、避免硬编码路径,敏感信息应加密。适用于中小型项目配置管理。

Java的Properties类是处理配置文件的常用工具,特别适合读取以键值对形式存储的文本文件(通常为.properties格式)。它继承自Hashtable,提供了方便的方法来加载、读取和保存配置信息。
在项目资源目录下创建一个名为 config.properties 的文件,内容如下:
database.url=jdbc:mysql://localhost:3306/mydb database.username=root database.password=123456 app.name=MyApplication app.version=1.0
该文件定义了数据库连接和应用基本信息。
通过ClassLoader或FileInputStream读取配置文件。推荐使用类路径方式,便于打包后访问。
立即学习“Java免费学习笔记(深入)”;
示例代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
private Properties props = new Properties();
public void loadConfig() {
// 使用类加载器读取资源文件
try (InputStream input = getClass().getClassLoader()
.getResourceAsStream("config.properties")) {
if (input == null) {
System.out.println("无法找到配置文件!");
return;
}
// 加载配置文件
props.load(input);
System.out.println("配置文件加载成功!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getProperty(String key) {
return props.getProperty(key);
}
public static void main(String[] args) {
ConfigReader reader = new ConfigReader();
reader.loadConfig();
// 读取配置项
System.out.println("数据库地址: " + reader.getProperty("database.url"));
System.out.println("用户名: " + reader.getProperty("database.username"));
System.out.println("应用名称: " + reader.getProperty("app.name"));
}
}
null。确保config.properties文件位于src/main/resources(Maven/Gradle项目)目录下,这样才能被正确加载。避免硬编码文件路径,使用类路径加载更稳定。
读取敏感信息如密码时,考虑加密处理,不要明文存储。
基本上就这些,Properties类简单易用,适合中小型项目的配置管理。以上就是如何利用Java的Properties类读取配置文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号