JDK1.6下 ResourceBundle 本身提供了 ResourceBundle.clearCache(); 方法,在eclipse 下正常测试都是可以正常刷新到修改后资源文件的值,不过当部署到tomcat下后,ResourceBundle.clearCache();这个方法, 看起来就不起作用了。
经过一翻调试,终于可以了,贴上代码:
private static ResourceBundle resourceBundle;
private static long lastUpdateTime = 0l;
private static final Logger LOGGER = Logger.getLogger(ResourceBundleService.class);
private ResourceBundleService() {
}
/**
* 载入 ResourceBundle
*/
public static void loadResourceBundle() {
try {
// 这个是必须的
ResourceBundle.clearCache();
//产生ResourceBundle对象时,
//重写ResourceBundle.Control 的newBundle方法,
//将reload标识位置为true
resourceBundle = ResourceBundle.getBundle("resource", new Locale(GameConfig.locale.substring(0, 2),
GameConfig.locale.substring(3, 5)), new ResourceBundle.Control() {
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
boolean reload) throws IllegalAccessException, InstantiationException, IOException {
// 将reload标识位置为true
return super.newBundle(baseName, locale, format, loader, true);
}
});
lastUpdateTime = System.currentTimeMillis();
} catch (MissingResourceException e) {
LOGGER.error("There is no " + GameConfig.locale + " resource file found!!");
}
}
/**
* 资源文件有改动时才会重新载入 ResourceBundle
*/
public static void reloadResourceBundle() {
final String absPath = Thread.currentThread().getContextClassLoader().getResource("").getPath().replaceAll(
"%20", " ");
final StringBuffer resourceFullName = new StringBuffer(512);
resourceFullName.append(absPath);
resourceFullName.append("resource_");
resourceFullName.append(GameConfig.locale);
resourceFullName.append(".properties");
final File resFile = new File(resourceFullName.toString());
if (resFile.exists()) {
if (resFile.lastModified() > lastUpdateTime) {
System.out.println(("lastUpdateTime==" + lastUpdateTime + " Curr lastModified:" + resFile
.lastModified()));
ResourceBundleService.loadResourceBundle();
}
} else {
LOGGER.error("resorce file not found :" + resourceFullName.toString());
}
}
主要做了两个事:
1.调用了ResourceBundle.clearCache();
2.产生ResourceBundle对象时, 重写ResourceBundle.Control 的newBundle方法,
将reload标识位置为true
定时检测到资源文件,有改动时重生成ResourceBundle实例,就可以获取到最新的资源文件值。