用“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;
}
}