java读取配置文件的方法

1、基于ClassLoder读取配置文件

注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

InputStream inputStream1 = PropertiesTest.class.getResourceAsStream("filepath");

2、基于 InputStream 读取配置文件

注意:该方式的优点在于可以读取任意路径下的配置文件。

InputStream inputStream1 = new BufferedInputStream(new FileInputStream("filepath"));

3、举例:

(1)结构:
在这里插入代码结构图片描述
(2)代码

public class PropertiesUtil {

    public static final PropertiesUtil INSTANCE = new PropertiesUtil();
    public static PropertiesUtil getInstance(){
        return INSTANCE;
    }

    /**
     * 1.使用getResourceAsStream读取配置文件
     */
    public void readPropertiesByGetSourceAsStream(){

        // 1.src下面com/demo/config包内的配置文件config1.properties
        InputStream inputStream1 = PropertiesTest.class.getClassLoader().getResourceAsStream("com/demo/config/config1.properties");

        // 2.读取和PropertiesTest位于同一个包内的配置文件config2.properties
        InputStream inputStream2 = PropertiesTest.class.getResourceAsStream("config2.properties");

        // 3.读取src根目录下的配置文件config3.properties
        InputStream inputStream3 = PropertiesTest.class.getClassLoader().getResourceAsStream("config3.properties");

        // 4.读取位于另外一个resource文件夹里面的配置文件config4.properties
        InputStream inputStream4 = PropertiesTest.class.getClassLoader().getResourceAsStream("config4.properties");

        Properties properties = new Properties();
        System.out.println("使用getResourceAsStream()配置文件...");

        try {
            System.out.println("-----读取inputStream1开始-----");
            properties.load(inputStream1);
            System.out.println("config1.properties:username = "+properties.getProperty("username") + ",password = " +properties.getProperty("password") +",url = " + properties.getProperty("url"));
            System.out.println("-----读取inputStream1结束-----");
            System.out.println("---------------------------------------------");

            System.out.println("-----读取inputStream2开始-----");
            properties.load(inputStream2);
            System.out.println("config2.properties:username = "+properties.getProperty("username") + ",password = " +properties.getProperty("password") +
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值