I want to load multiple property files from various packages as ResourceBundle. Can I achieve that in Java
getBundle. Gets a resource bundle using the specified base name, locale, and class loader. This method behaves the same as calling getBundle(String, Locale, ClassLoader, Control) passing a default instance of ResourceBundle.
ResourceBundle class is used to store text and objects which are locale sensitive. Generally we use property files to store locale specific text and then represent them using ResourceBundle object. Following are the steps to use locale specific properties file in a java based application.
Create a new resource bundleFrom the main menu, select File | New | Resource Bundle, or press Alt+Insert and click Resource Bundle. In the dialog that opens, specify the base name of the resource bundle. If necessary, select the Use XML-based properties files.
The ResourceBundle class is used to internationalize the messages. In other words, we can say that it provides a mechanism to globalize the messages. The hardcoded message is not considered good in terms of programming, because it differs from one country to another.
Extend java.util.PropertyResourceBundle
and call setParent
.
Here is my implementation:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
public class CombinedResourceBundle extends ResourceBundle
{
private Map<String, String> combinedResources = new HashMap<>();
private List<String> bundleNames;
private Locale locale;
private Control control;
public CombinedResourceBundle(List<String> bundleNames, Locale locale, Control control)
{
this.bundleNames = bundleNames;
this.locale = locale;
this.control = control;
}
public void load()
{
bundleNames.forEach(bundleName ->
{
ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale, control);
Enumeration<String> keysEnumeration = bundle.getKeys();
ArrayList<String> keysList = Collections.list(keysEnumeration);
keysList.forEach(key -> combinedResources.put(key, bundle.getString(key)));
});
}
@Override
public Object handleGetObject(String key)
{
return combinedResources.get(key);
}
@Override
public Enumeration<String> getKeys()
{
return Collections.enumeration(combinedResources.keySet());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With