How to ignore the system default Locale to retrieve resourceBundle

谁说我不能喝 提交于 2019-12-07 03:10:03

问题


I am localizing a web application using a java.util.ResourceBundle class and property files.

I have two locales, fr_FR and en_US, and I want to use en_US as the default, so I wrote the following files :

  • messages_fr_FR.properties with fr_FR messages
  • messages.properties with en_US messages

My problem is that the ResourceBundle.getBundle(BUNDLE_NAME, locale) method fall back Locale.getDefault() before using the default property file, which means if the JVM Locale is set to fr_FR, ResourceBundle.getBundle("name", new Locale("en", "US")) returns the fr_FR bundle.

I could rename the messages.properties file, but this could returns a MissingResourceException with other desired and default locales.

How can I ignore the System Locale, without duplicating the property file or calling Locale.setDefault ?


回答1:


You can do that by using a custom ResourceBundle.Control, either by overloading the getFallbackLocaleexplicitly, or by using :

ResourceBundle.getBundle("name", new Locale("en", "US"), ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_PROPERTIES))



回答2:


The bundle you are looking for is called the baseBundle, and it can be obtained with ease using Locale.ROOT as the Locale. Like this:

ResourceBundle.getBundle("bundle name",Locale.ROOT)


来源:https://stackoverflow.com/questions/26422727/how-to-ignore-the-system-default-locale-to-retrieve-resourcebundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!