动态读取properties文件内容

使用“ClassLoader.getResourceAsStream”读取properties文件时,修改文件后重新执行,读入的仍是修改前的参数。原因是该方法读入后会将.properties文件保存在缓存中,重新执行时从缓存读取,而非再次读取文件。

用“ClassLoader.getResourceAsStream”读取properties文件时会发现修改了.properties后,即使重新执行,读入的仍为修改前的参数。此问题的原因在于ClassLoader.getResourceAsStream读入后,会将.properties保存在缓存中,重新执行时会从缓存中读取,而不是再次读取.properties文件。

动态读取的代码如下:

import java.util.Properties;
 
/**
 * 实时动态获取properties文件的值
 * @author Administrator
 *
 */
public class demo01 {
    /**
     * 根据配置变量实时获取配置文件中的值
     * @param key 配置名
     * @param filePath 配置文件路径名,例如:test.properties
     * @return 配置值
     */
    public static String getCurrentPropertiesValue(String key,String filePath){
        String value="";
        Properties p = new Properties();
        try {
            //非实时动态获取
            //p.load(new InputStreamReader(this.class.getClassLoader().getResourceAsStream(filePath), "UTF-8"));
            //下面为动态获取
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            InputStream is = new FileInputStream(path +File.separator+ filePath);
            p.load(is);
            value=p.getProperty(key);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值