public static Properties properties;
static {
properties = new Properties();
//得到classpath路径
URL url = PropertiesUtil.class.getClassLoader().getResource("");
File file = new File(url.getFile());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile()&&f.getName().endsWith("properties")) {//遍历出所有properties文件
try {
properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
由于配置文件加载是一个耗时操作,开发时不应该在使用配置文件的时候实时读取配置文件,应该编写一个工具类,该代码放在工具类的静态代码块中,初始化时一次加载所有的配置文件。
用如下方法读取
public static String getValue(String key)
{
return properties.getProperty(key);
}
本文介绍了一种高效加载配置文件的方法,通过静态代码块在类初始化时一次性加载所有配置文件,避免了运行时重复读取造成的性能损耗。提供了一个实用的工具类示例,用于在Java应用中管理配置。
2194





