设置
假设我有两个字符串文件:
Strings_en.properties
Strings_fr.properties假设英语是默认的语言,所有的字符串都存在,而法语则落后,有些字符串缺失了。
期望行为
在这两种情况下,我想回到英语方面来:
ResourceBundle.getBundle("path/to/Strings", Locale.GERMAN);
ResourceBundle.getBundle("path/to/Strings", Locale.FRENCH).getString("only.in.english");
第一个回退非常简单:根据文档,将英语作为默认区域设置就足够了,例如通过设置Locale.setDefault(Locale.ENGLISH);。
问题
我的问题是第二个退路。如果在Strings_fr中找不到字符串,则继续查找“父包”:getObject()文档。但是,Strings_en不是Strings_fr的父级,而是抛出一个MissingResourceException。
解决办法
一个简单的解决方法是将Strings_en.properties重命名为Strings.properties。这使得它成为Strings_fr (以及其他任何Strings_ )的父包,查找缺少的字符串将返回默认的英文版本。
Problem:系统现在有一个默认的本地化,但它不再理解存在英语本地化。
变通方法2
获取字符串时,检查它是否存在于包中--如果没有,则从英文字符串中提取字符串。
ResourceBundle bundle = ResourceBundle.getBundle("path/to/Strings", Locale.FRENCH);
if (bundle.containsKey(key)) { return bundle.getString(key); }
return ResourceBundle.getBundle("path/to/Strings", DEFAULT_WHICH_IS_ENGLISH).getString(key);Problem:这只是一次黑客攻击,我相信有一种“有意”的方法。
问题
是否有简单的方法使Strings_en成为Strings_fr的父级?如果不是,例如,将Strings_en硬链接到Strings是否合理,这样我就可以将英语作为一个显式的本地化,同时作为默认的本地化。
发布于 2016-03-15 13:06:21
您可以将Strings_en.properties重命名为Strings.properties (使英语成为默认的本地化),并添加一个新的空 Strings_en.properties。
然后
ResourceBundle.getBundle("path/to/Strings", Locale.ENGLISH).getLocale()还返回Locale.ENGLISH。
发布于 2021-02-25 18:10:42
旧线程,另一种解决方案:您可以使用ResourceBundle.Control和getCandidateLocales添加自定义语言候选项(文件后缀)
ResourceBundle.getBundle(baseName, locale, new ResourceBundle.Control() {
@Override
public List<Locale> getCandidateLocales(String baseName, Locale locale) {
List<Locale> list = super.getCandidateLocales(baseName, locale);
list.add(new Locale("en"));
return list;
}
}https://stackoverflow.com/questions/36011759
复制相似问题