使用java中的资源包在国际化中加载多个特定于区域设置的属性文件



我有四个属性文件

  1. Application.properties
  2. Application_fr_fr.properties
  3. Database.properties
  4. 数据库_fr_fr.properties

因此,现在我需要在多个程序中进行国际化,因此现在我需要加载多个属性文件,并从特定于区域设置的属性文件中获取键值对。为此,我有一个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??
    }
}

希望问题清楚。

您需要在getLabel中每次调用ResourceBundle.getBundle(baseName, locale)。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);
}

暂时使用Application_fr.properties<加拿大人会感激的。使用Locale.setDefault(availableLocale)选择一个可用的区域设置。根区域设置属性Application.properties也应该包含语言键。你可以复制法国的。在这种情况下,您不需要设置默认的区域设置。>

让我们在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内部。

最新更新