我想从各种包中加载多个属性文件作为ResourceBundle。我可以在Java中实现吗
答案 0 :(得分:3)
扩展java.util.PropertyResourceBundle
并致电setParent
。
答案 1 :(得分:0)
ResourceBundle.Control()控制ResourceBundle的文件列表。你可以覆盖 getCandidateLocales和toBundleName。 toBundleName将语言环境转换为“文件名”以及可以在getCandidateLocales中控制的语言环境列表。 例如
final String[] variants = new String[]{"your names"};
ResourceBundle.getBundle(baseName, locale,
new ResourceBundle.Control() {
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
List<Locale> out = new ArrayList<Locale>();
String language = locale.getLanguage();
String country = locale.getCountry();
for (String variant : variants) {
out.add(new Locale(language, country, variant));
}
out.addAll(super.getCandidateLocales(baseName, locale));
return out;
}
public String toBundleName(String baseName, Locale locale) {
Locale l = new Locale(locale.getLanguage(), locale.getCountry());
return locale.getVariant() + "." + super.toBundleName(baseName, l);
}
});
仅适用于Java 1.6
答案 2 :(得分:0)
看看这堂课。它非常适合我!课程的Javadoc解释了如何使用它。
MultiplePropertiesResourceBundle (+子公司ResourceBundleEnumeration)
在这里,您可以找到有用的unit-tests a.k.a.代码文档。
答案 3 :(得分:0)
这是我的实施:
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());
}
}