Java 无论当前的默认语言环境如何,如何获取默认的 ResourceBundle
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24305512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the default ResourceBundle regardless of current default Locale
提问by
I have three resource files in class path:
我在类路径中有三个资源文件:
labels.properties:
标签.属性:
language = Default
labels_en.properties:
label_en.properties:
language = English
labels_fr.properties:
标签_fr.properties:
language = French
Is there a way to get a ResourceBundle
object that always loads labels.properties
NO MATTER what my default Locale
is?
有没有办法获得一个ResourceBundle
始终加载的对象,labels.properties
无论我的默认值Locale
是什么?
ResourceBundle.getBundle("labels")
returns the one corresponding to the current default locale (as expected).
ResourceBundle.getBundle("labels")
返回对应于当前默认语言环境的那个(如预期的那样)。
The only way I can find is to set the default locale to a non-existing locale, but this may break other modules.
我能找到的唯一方法是将默认语言环境设置为不存在的语言环境,但这可能会破坏其他模块。
Thank you!
谢谢!
Locale.setDefault( Locale.ENGLISH);
Assert.assertEquals( "English", ResourceBundle.getBundle( "labels").getString( "language"));
Locale.setDefault( Locale.FRENCH);
Assert.assertEquals( "French", ResourceBundle.getBundle( "labels").getString( "language"));
Assert.assertEquals( "French", ResourceBundle.getBundle( "labels", new Locale( "do-not-exist")).getString( "language"));
Locale.setDefault( new Locale( "do-not-exist"));
Assert.assertEquals( "Default", ResourceBundle.getBundle( "labels").getString( "language"));
采纳答案by VGR
You can pass in a ResourceBundle.Controlwhich, regardless of requested Locale, always searches only the root ResourceBundle:
您可以传入一个ResourceBundle.Control,无论请求的区域设置如何,它始终只搜索根 ResourceBundle:
ResourceBundle rootOnly = ResourceBundle.getBundle("labels",
new ResourceBundle.Control() {
@Override
public List<Locale> getCandidateLocales(String name,
Locale locale) {
return Collections.singletonList(Locale.ROOT);
}
});
回答by Michel Fortes
Another way is to set the default locale of your application, like
另一种方法是设置应用程序的默认语言环境,例如
Locale.setDefault(Locale.US);