I18NUtils.java

package info.textgrid.rep.i18n;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;

public class I18NUtils {

  public static HashMap<String, String> getTranslationMap(Locale locale) {
    HashMap<String, String> messages = new HashMap<String, String>();
    ResourceBundle rb = ResourceBundle.getBundle("i18n.Language", locale, new UTF8Control());
    for (String key : rb.keySet()) {
      messages.put(key, rb.getString(key));
    }
    return messages;
  }

  // read resource bundle in utf8: http://stackoverflow.com/a/4660195
  private static class UTF8Control extends Control {
    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format,
        ClassLoader loader, boolean reload)
        throws IllegalAccessException, InstantiationException, IOException {
      // The below is a copy of the default implementation.
      String bundleName = toBundleName(baseName, locale);
      String resourceName = toResourceName(bundleName, "properties");
      ResourceBundle bundle = null;
      InputStream stream = null;
      if (reload) {
        URL url = loader.getResource(resourceName);
        if (url != null) {
          URLConnection connection = url.openConnection();
          if (connection != null) {
            connection.setUseCaches(false);
            stream = connection.getInputStream();
          }
        }
      } else {
        stream = loader.getResourceAsStream(resourceName);
      }
      if (stream != null) {
        try {
          // Only this line is changed to make it to read properties files as UTF-8.
          bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
        } finally {
          stream.close();
        }
      }
      return bundle;
    }
  }

}