java读取配置文件

一、针对不会经常变化的文件

    通过*.class.getClassLoader().getResourceAsStream读取文件之后,会把文件存在内存中缓存,后来每一次读取都是读取内存中的内容了,而不是再次读取,同理ResourceBundle.getBundle("resource/config")。

    eg:

    1、 public static Properties newInstance() {

        InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties");
        Properties p = new Properties();
        try {
            p.load(is);
        } catch (IOException e) {
            logger.error("读取配置文件出错", e);
        }
        return p;

    }

    //获取key

     PropertiesUtil.newInstance().getProperty("key");

2、private static final ResourceBundle config = ResourceBundle.getBundle("config");
    public static final String getValue(String key) {
        return config.getString(key);

    }

二、需要实时加载变化文件

    -- 方法1、改变一下文件的输入流获取方式

    Properties prop = new Properties();
    String path = CommonUtils.class.getClassLoader().getResource("config.properties").getPath();
    InputStream is = new FileInputStream(path);
    prop.load(is);

    -- 方法2
    //获取ClassPath的绝对URI路径
    String dirPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    //获取config.properties文件,针对在classPath最外层情况
    File file = new File(dirPath,"config.properties");
     props = new Properties();
     InputStream fis = new FileInputStream(file);
     props.load(fis);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值