簡體   English   中英

使用Java中的資源包以國際化方式加載多個特定於語言環境的屬性文件

[英]Load multiple locale specific properties files in internationalization with resource bundle in java

我有四個屬性文件

  1. Application.properties
  2. Application_fr_FR.properties
  3. Database.properties
  4. Database_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維護內部緩存,因此不會每次都加載所有props文件:

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; les Canadiens非常感謝。 使用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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM