JDK1.6 ResourceBundle 在tomcat下刷新资源文件

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实例,就可以获取到最新的资源文件值。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值