目录
- java 实时动态获取properties文件的内容
- Java 读取配置文件 Properties VS ResourceBundle
- 1. 常用API
- 2. Properties 解析属性文件
- 3. ResourceBundle 解析属性文件
- 4. 属性文件
- 5. 实战推荐
java 实时动态获取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=https://www.it610.com/article/p.getProperty(key);
} catch (UnsupportedEncodingException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
}return value;
}}
【java如何实时动态获取properties文件的内容】
Java 读取配置文件 Properties VS ResourceBundle
在java开发中, 对于一些常用的配置性的信息, 通常会采用存放在属性文件中, 因为修改配置文件无须重新编译jar包. 对于属性文件,通常可以使用Properties和ResourceBundle 两个类来解析. 需要注意的是, 默认情况下java工程中的*.properties文件编码格式是ISO-8859-1, Properties和ResourceBundle也是按照ISO-8859-1格式来解析属性文件中字符串的. 所以对于解析包含中文的熟悉文件时,需要额外注意.
- ResourceBundle: 通常用于解析国际化资源属性文件, 会根据本地环境自动选择对应的国际化资源.
- Properties: 用来解析普通属性文件
1. 常用API
1.1 Properties 常用API
Properties 继承Hashtable