Explore how ResourceBundle processes keys across multiple property files for different locales.
Introduction
The ResourceBundle
class in Java is a powerful tool for managing locale-specific resources.
When multiple property files are available, it merges and retrieves keys and values based on the specified
locale. However, the order in which these keys are returned may sometimes surprise developers.
How ResourceBundle Works
When a ResourceBundle
is created using the getBundle()
method:
-
It first looks for the most specific property file matching the requested locale.
For example,
mymsgs_en_UK.properties
for theen_UK
locale. -
If keys are missing in the locale-specific file, it falls back to the default
property file (e.g.,
mymsgs.properties
).
The merged result includes all keys from both files, prioritizing locale-specific values.
Code Example
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
public class LocalizationExample {
public static void main(String[] args) {
Locale myloc = new Locale.Builder().setLanguage("en").setRegion("UK").build();
ResourceBundle msgs = ResourceBundle.getBundle("mymsgs", myloc);
Enumeration<String> en = msgs.getKeys();
while (en.hasMoreElements()) {
String key = en.nextElement();
String val = msgs.getString(key);
System.out.println(key + " : " + val);
}
}
}
Sample Property Files
Default File: mymsgs.properties
okLabel=OK
cancelLabel=Cancel
Locale-Specific File: mymsgs_en_UK.properties
okLabel=YES
noLabel=NO
Output
When the above code is executed, the following output is observed:
noLabel : NO
okLabel : YES
cancelLabel : Cancel
Explanation
The output order is determined by how ResourceBundle
merges and retrieves keys:
- It processes keys from the locale-specific file first (
mymsgs_en_UK.properties
). - It then adds keys from the default file (
mymsgs.properties
) that are not already included.
This results in the following merged key order:
noLabel
, okLabel
, and cancelLabel
.
Values are fetched from their respective sources based on priority.
Conclusion
The ResourceBundle
lookup mechanism ensures seamless localization by combining resources from
multiple files. Understanding this behavior helps in designing and debugging locale-specific applications.
0 Comments