登录
首页 >  文章 >  java教程

Java读取Properties文件的几种方法

时间:2026-01-27 10:31:31 275浏览 收藏

积累知识,胜过积蓄金银!毕竟在文章开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《Java读取Properties配置文件方法大全》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

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

java怎么读取properties配置文件 读取与加载Properties配置文件的方法

Java中读取与加载Properties配置文件的方法非常常见,主要用于管理应用程序的配置信息。下面介绍几种常用的方式。

1. 使用Class.getResourceAsStream()读取配置文件

适用于将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);

2. 使用FileInputStream读取外部文件

当配置文件位于项目外部路径时,可以使用FileInputStream方式读取。

Properties prop = new Properties();
FileInputStream input = new FileInputStream("D:/config/app.properties");
prop.load(input);
String value = prop.getProperty("key");

注意:这种方式依赖绝对路径或相对路径,部署时需确保文件可访问。

3. 使用ClassLoader.getSystemResourceAsStream()

与第一种类似,但通过系统类加载器加载资源。

Properties prop = new Properties();
InputStream is = ClassLoader.getSystemResourceAsStream("config.properties");
if (is != null) {
    prop.load(is);
}

4. 静态工具类封装读取方法

实际开发中通常封装成工具类,便于复用。

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")

基本上就这些常用方式。关键是根据配置文件的位置选择合适的加载方法,推荐将配置文件放在resources目录下,使用类路径加载更稳定。

今天关于《Java读取Properties文件的几种方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>