Java读取properties配置文件工具类

本文介绍了一种在Java中读取properties配置文件的方法,通过使用InputStreamReader和Properties类的getProperty()方法,从配置文件中读取键值对数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java读取properties配置文件的方式

一.背景

Java读取 properties 配置文件的方式,主要是通过 getProperty() 方法。config.properties 文件中有诸如 config.a = xxx 这样的存储形式,下面代码是读取 properties 配置文件中参数数据到 String 类型变量中。

二.代码片段

// 新建一个拥有 config.properties 相对项目路径的 File 对象
File propertiesFile = new File("src/main/resources/config.properties");
// 初始化输入流 reader,利用相对项目路径生成的 File 来获取其绝对路径,并且以 utf-8 形式读取 properties 配置文件
InputStreamReader propertiesReader = new InputStreamReader(new FileInputStream(propertiesFile.getAbsolutePath()), "UTF-8");
// 定义 Properties 对象 properties
Properties properties = new Properties();
// 通过 Properties 类的 load 方法来读取 properties 文件中的变量
properties.load(propertiesReader);
// 开始读取 properties 文件中数据
String a = properties.getProperty("conf.a");
String b = properties.getProperty("conf.b");
String c = properties.getProperty("conf.c");

三.完整工具类代码

public class PropertiesReader {
    /**
     * 配置文件
     */
    private static Properties properties = new Properties();

    /**
     * 读取 properties 测试项目配置文件
     *
     * @param propertiesPath 配置文件路径
     * @return Properties
     * @throws IOException IOException
     */
    public static Properties readProperties(String propertiesPath) throws IOException {
        log.info("读取项目配置文件");
        InputStream inputStream = new FileInputStream(propertiesPath);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        properties.load(bufferedReader);
        return properties;
    }

    /**
     * 依据键名获取配置文件中的键值
     *
     * @param key 键名
     * @return 键值
     */
    public static String getKey(String key) {
        return properties.getProperty(key);
    }

readProperties 方法中的参数是.properties配置文件的相对路径,比如src/main/resources,getkey 方法用来依据键取出值

.properteis文件内容怎么写呢?如下:

############### redis ##############
# redis ip
redis.ip=192.168.16.109
# redis port
redis.port=6379
# redis password
redis.pwd=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值