2013-06-25 26 views
0

資源包我有四個屬性文件加載多個區域特定的屬性文件在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?? 
    } 
} 

希望這個問題很清楚。

回答

2

您需要撥打ResourceBundle.getBundle(baseName, locale)每次getLabel。資源包維護內部緩存,因此它不會加載所有的道具,每次文件:

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

噢謝謝你有關內部緩存的信息,但是我如何調用多個屬性文件?????? –

+0

我懷疑這是比試圖在應用程序中首先找到的更好的解決方案,如果在數據庫中找不到,請參閱更新 –

0

暫時使用Application_fr.properties; les Canadiens將會感恩。用Locale.setDefault(availableLocale)選擇一個可用的語言環境。根區域設置屬性Application.properties還應該包含語言鍵。你可以複製法文版。在這種情況下,您無需設置默認語言環境。

+0

如何在同一時間加載Database.properties和Application.properties,以便我可以爲ResourceBundle提供一個訪問點? –

+0

@EvgenlyDorofeev回答說。不要試圖爲所有人使用額外的地圖,因爲套件已經過優化。 'getLabel(String rIx,Locale,ResourceBundle ... bundles)'也可能有其用處。 –

0

讓檢查github此實現它的作品真的很好。它需要下面的函數命名約定:

MultiplePropertiesResourceBundle是一個抽象的基本實現,允許一個資源包從,而這些屬性文件必須使用相同的名稱結尾的多個屬性文件合併 - 基名稱爲這些組合資源包。

如果你在第一次使用它,你需要實現如下抽象類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回購。