Search code examples
javainternationalizationresourcebundle

In Java how do I find out what languages I have available my Resource Bundle


I have some resource bundles packaged in my main jar

widget_en.properties
widget_de.properties

I retrieve a resource bundle based on my default locale as folows

ResourceBundle.getBundle("widget", Locale.getDefault());

But I want to present the user with a list of available languages supported so that can select a language that may be different to their computers default

But I can't find a method in ResourceBundle that would list available locales, I don't want to hardcode a list as I may forget to update it when another resource bundle is added.

EDIT

As I only resource bundles for different language (I dont have country refinements) so I have got generated a list by iterating through all the known language codes and check for each one as a resource.

String[]langs = Locale.getISOLanguages();
for(String lang:langs)
{
      URL rb = ClassLoader.getSystemResource("widget_"+lang+".properties");
      if(rb!=null)
      {
            System.out.println("Found:"+rb.toString());
      }
}

Solution

  • I don't think there is an API for this because new valid locale objects can be created on the fly:

    Locale locale = new Locale("abcd");
    

    without the need to register it somewhere. And then you can use a resource bundle widget_abcd.properties without restrictions:

    ResourceBundle resource= ResourceBundle.getBundle("widget", new Locale("abcd"));
    

    From the java.util.Locale API docs:

    Because a Locale object is just an identifier for a region, no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct, you must query those resources.

    To solve the problem you can still iterate over all files called "widget_" in the resource directory and discover the new added resource bundles.

    Note that Locale.getAvailableLocales() is not 100% sure for the above reason: you might some day define a non standard locale. But if you'll add only a few standard locales you can use this static method to iterate over the system locales and get the corresponding bundles.