How to get the default ResourceBundle regardless of current default Locale

user1089451 picture user1089451 · Jun 19, 2014 · Viewed 15.3k times · Source

I have three resource files in class path:

labels.properties:

language = Default

labels_en.properties:

language = English

labels_fr.properties:

language = French

Is there a way to get a ResourceBundle object that always loads labels.properties NO MATTER what my default Locale is?

ResourceBundle.getBundle("labels") returns the one corresponding to the current default locale (as expected).

The only way I can find is to set the default locale to a non-existing locale, but this may break other modules.

Thank you!

Locale.setDefault( Locale.ENGLISH);
Assert.assertEquals( "English", ResourceBundle.getBundle( "labels").getString( "language"));
Locale.setDefault( Locale.FRENCH);
Assert.assertEquals( "French", ResourceBundle.getBundle( "labels").getString( "language"));
Assert.assertEquals( "French", ResourceBundle.getBundle( "labels", new Locale( "do-not-exist")).getString( "language"));
Locale.setDefault( new Locale( "do-not-exist"));
Assert.assertEquals( "Default", ResourceBundle.getBundle( "labels").getString( "language"));

Answer

VGR picture VGR · Jun 20, 2014

You can pass in a ResourceBundle.Control which, regardless of requested Locale, always searches only the root ResourceBundle:

ResourceBundle rootOnly = ResourceBundle.getBundle("labels",
    new ResourceBundle.Control() {
        @Override
        public List<Locale> getCandidateLocales(String name,
                                                Locale locale) {
            return Collections.singletonList(Locale.ROOT);
        }
    });