使用Class.getResourceAsStream()读取src目录下的配置文件,通过类加载器加载;2. 使用FileInputStream读取外部路径文件,需确保部署时路径可访问;3. 使用ClassLoader.getSystemResourceAsStream()通过系统类加载器读取;4. 封装静态工具类ConfigUtil实现配置文件的集中管理与复用。推荐将配置文件置于resources目录下,利用类路径加载以提升稳定性与可维护性。

Java中读取与加载Properties配置文件的方法非常常见,主要用于管理应用程序的配置信息。下面介绍几种常用的方式。
适用于将properties文件放在src目录下(编译后在classes目录),通过类加载机制读取。
示例代码:
config.properties 文件内容:
username=admin
password=123456
Java代码读取:
Properties prop = new Properties();
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
if (input != null) {
prop.load(input);
}
String user = prop.getProperty("username");
String pass = prop.getProperty("password");
System.out.println("User: " + user + ", Pass: " + pass);
当配置文件位于项目外部路径时,可以使用FileInputStream方式读取。
Properties prop = new Properties();
FileInputStream input = new FileInputStream("D:/config/app.properties");
prop.load(input);
String value = prop.getProperty("key");
注意:这种方式依赖绝对路径或相对路径,部署时需确保文件可访问。
立即学习“Java免费学习笔记(深入)”;
与第一种类似,但通过系统类加载器加载资源。
Properties prop = new Properties();
InputStream is = ClassLoader.getSystemResourceAsStream("config.properties");
if (is != null) {
prop.load(is);
}
实际开发中通常封装成工具类,便于复用。
public class ConfigUtil {
private static final Properties props = new Properties();
static {
try (InputStream input = ConfigUtil.class.getClassLoader()
.getResourceAsStream("application.properties")) {
if (input == null) {
throw new IllegalArgumentException("配置文件未找到!");
}
props.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
}
调用方式:ConfigUtil.getProperty("username")
以上就是java怎么读取properties配置文件 读取与加载Properties配置文件的方法的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号