使用java中的资源包在国际化中加载多个特定于语言环境的属性文件

时间:2013-06-25 09:43:43

标签: java properties locale resourcebundle

我有四个属性文件

  1. Application.properties
  2. Application_fr_FR.properties
  3. Database.properties
  4. Database_fr_FR.properties
  5. 所以现在我需要在多个程序中进行国际化,所以现在我需要加载多个属性文件,并从特定于语言环境的属性文件中获取键值对值。为此,我有一个ResourceBundleService.java

    public class ResourceBundleService {
        private static String language;
        private static String country;
        private static Locale currentLocale;
        static ResourceBundle labels;
        static {
            labels = ResourceBundle
                    .getBundle("uday.properties.Application");
            labels = append(Database.properties");
            //** how to append existing resource bundle with new properties file?
        }
    
        public static String getLabel(String resourceIndex, Locale locale) {
            return labels.getString(resourceIndex);
            //How to get locale specific messages??
        }
    }
    

    希望问题很明确。

3 个答案:

答案 0 :(得分:5)

您需要每次ResourceBundle.getBundle(baseName, locale)致电getLabel。 ResourceBundle维护一个内部缓存,因此每次都不会加载所有道具文件:

public static String getLabel(String resourceIndex, Locale locale) {
    ResourceBundle b1 = ResourceBundle.getBundle("uday.properties.Application", locale);
    if (b1.contains(resourceIndex)) {
       return b1.getString(resourceIndex);
    }
    ResourceBundle b2 = ResourceBundle.getBundle("uday.properties.Database", locale);
    return b2.getString(resourceIndex);
}

答案 1 :(得分:0)

暂时使用Application_fr.properties; les Canadiens 将会感激不尽。使用Locale.setDefault(availableLocale)选择可用的区域设置。根区域设置属性Application.properties也应包含语言键。你可以复制法国的。在这种情况下,您无需设置默认语言环境。

答案 2 :(得分:0)

让我们在github上检查一下这个实现是否真的很好。它需要以下函数命名约定:

  

MultiplePropertiesResourceBundle是一个抽象基础实现,允许组合来自多个属性文件的ResourceBundle,而这些属性文件必须以相同的名称结尾 - 这些组合的ResourceBundle的基本名称。

如果您在第一次使用它,则需要实现抽象类MultiplePropertiesResourceBundle,如下所示:

import ch.dueni.util.MultiplePropertiesResourceBundle;

public class CombinedResources extends MultiplePropertiesResourceBundle {

    public  CombinedResources() {
        super("package_with_bundles");
    }

}

然后你应该实现延伸出CombinedResources的空类:

public class CombinedResources_en extends CombinedResources {}

等等其他语言。之后,您可以使用您的包,如下所示:

ResourceBundle bundle = ResourceBundle.getBundle("CombinedResources");

此捆绑包将使用package_with_bundles内的所有属性文件。有关更多信息,请查看github repo。