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

后端 未结 4 2046
梦如初夏
梦如初夏 2021-01-01 11:26

I have some resource bundles packaged in my main jar

widget_en.properties
widget_de.properties

I retrieve a resource bundle based on my de

4条回答
  •  无人及你
    2021-01-01 11:47

    If you really package the resource files inside your JAR, then I would do it like this:

    public static void main(String[] args) {
      Set resourceBundles = getResourceBundles(A.class.getName());
      if (resourceBundles.isEmpty())
        // ...
    }
    
    public static Set getResourceBundles(String baseName) {
      Set resourceBundles = new HashSet<>();
    
      for (Locale locale : Locale.getAvailableLocales()) {
        try {
          resourceBundles.add(ResourceBundle.getBundle(baseName, locale));
        } catch (MissingResourceException ex) {
          // ...
        }
      }
    
      return Collections.unmodifiableSet(resourceBundles);
    }
    

    If you care about your JARs then you would at least get a set containing the default resource for a given baseName.

    If you have only resources with names like baseName_ this method works perfectly, because only those ResourceBundles will be added to the set which are present in your JAR. It'll work even if you decide you need separate baseName_en_US and baseName_en_UK resources, which is not unheard of.

    Shameless self-plug: I wrote a ResourceBundle.Control which takes a Charset as its argument, you might be interested in it if you want to load UTF-8 encoded resources files. It's available at GitHub.

提交回复
热议问题