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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:24:39  来源:igfitidea点击:

How to get the default ResourceBundle regardless of current default Locale

javainternationalizationlocaleresourcebundle

提问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 ResourceBundleobject that always loads labels.propertiesNO MATTER what my default Localeis?

有没有办法获得一个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);