OCP开闭原则来获取配置文件内容

该文章展示了两种在Java中读取src根目录下配置文件的方法。一种是通过getPath()获取文件绝对路径,然后使用FileReader读取;另一种是直接通过流的方式获取资源。在这两种情况下,都不会因文件路径改变而修改源码。最后,通过Properties对象的getProperty方法获取配置文件中的key对应的value。
摘要由CSDN通过智能技术生成

目前实现的功能就是只需要把配置文件放在src根目录下,就能用文件名读取到文件中的key&value

主要的代码就是获取这个文件的绝对路径,不会因为文件路径的改变从而去修改Java源码。

1、getPath()方式

package org.example.reflect;

import java.io.InputStream;
import java.util.Properties;

public class IoProperties {
    public static void main(String[] args) throws Exception{
        //获取绝对路径
        String path = Thread.currentThread().getContextClassLoader().getResource("文件名").getPath();
        FileReader reader = new FileReader();
        //新建配置对象
        Properties properties = new Properties();
        //将读取的文件流加载到配置对象
        properties.load(reader);
        //关闭流
        reader.close();
        //通过key获取value
        String className = properties.getProperty("className");
        //输出className
        System.out.println(className);
    }
}

2、以流的方式

package org.example.reflect;

import java.io.InputStream;
import java.util.Properties;

public class IoProperties {
    public static void main(String[] args) throws Exception{
        //以流的方式获取绝对路径
        InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("className.properties");
        //以下不变
        Properties properties = new Properties();
        properties.load(reader);
        reader.close();
        //通过key获取value
        String className = properties.getProperty("className");
        System.out.println(className);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值