ResourceBundle reads from 2 Properties files at the same time
-
20-02-2021 - |
Question
in my project I have 2 properties files
that are used for internationalization.
I use ResourceBundle
with Locale
parameter and I store the keys from properties files in a collection. Unfortunately in the collection are stored combined keys from both files. I just want keys from a single file depending on the locale. In my case the Locale is "bg_BG".
The properties files are:
time_intervals.properties
time_intervals_bg.properties
And this is how I am reading them:
public List<SelectItem> getTimeSpentList() {
timeSpentList = new ArrayList<SelectItem>();
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = ResourceBundle.getBundle("properties.time_intervals", context.getViewRoot().getLocale());
Enumeration<String> time_interval_keys = bundle.getKeys();
List<String> sortedKeys = new ArrayList<String>();
while(time_interval_keys.hasMoreElements()) {
String key = time_interval_keys.nextElement();
sortedKeys.add(key);
}
Collections.sort(sortedKeys, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.charAt(1) != ' ') {
return -1;
} else if (o2.charAt(1) != ' ') {
return 1;
}
return o1.compareTo(o2);
}
});
for (String key : sortedKeys) {
timeSpentList.add(new SelectItem(key));
}
if (timeSpentList == null || timeSpentList.isEmpty()) {
timeSpentList.add(new SelectItem(""));
return timeSpentList;
}
return timeSpentList;
}
The problem here is that in Enumeration<String> time_interval_keys
I get combined keys from both properties files after calling the bundle.getKeys()
but I want ONLY values from one of them. Please help.
P.S. Please let me know if anything is not clear about my explanations and about the code.
Solution
To expand on the answer by ago, you should have one group of resource files for the localized strings, and then a single separate file for the numerical values:
time_intervals.properties:
one_hour=1 hour
time_intervals_bg.properties:
one_hour=1 час
time_intervals.numbers.properties:
one_hour=1
Load the strings to display from time_intervals
, and the corresponding numerical values from time_intervals.numbers
.
EDIT: Or, if you're trying to use the numerical value to determine which string to display, then switch around the keys and values in your files, and forget about any time_intervals.numbers
file:
time_intervals.properties:
1=1 hour
time_intervals_bg.properties:
1=1 час
OTHER TIPS
You are not using the ResourceBundle system properly.
Each Property file should contain the same keys (or more precisely a subset of the keys declared in the base property file). When you ask for the value of a key (or when you list the key/values like you do), then the ResourceBundle tries to find the key in the most precise property file, defaulting to the default property file.
If the keys in the property files are different, then these keys are considered to be distinct.