在 Java 中,我如何找出我的资源包可用的语言

我的主 jar 中打包了一些资源包

I have some resource bundles packaged in my main jar

widget_en.properties
widget_de.properties

我根据我的默认语言环境检索资源包,如下所示

I retrieve a resource bundle based on my default locale as folows

ResourceBundle.getBundle("widget", Locale.getDefault());

但我想向用户展示支持的可用语言列表,以便可以选择可能与其计算机默认设置不同的语言

But I want to present the user with a list of available languages supported so that can select a language that may be different to their computers default

但我在 ResourceBundle 中找不到列出可用语言环境的方法,我不想硬编码列表,因为添加另一个资源包时我可能会忘记更新它.

But I can't find a method in ResourceBundle that would list available locales, I don't want to hardcode a list as I may forget to update it when another resource bundle is added.

编辑

因为我只有不同语言的资源包(我没有国家细化),所以我通过遍历所有已知的语言代码生成了一个列表,并将每个语言代码检查为资源.

As I only resource bundles for different language (I dont have country refinements) so I have got generated a list by iterating through all the known language codes and check for each one as a resource.

String[]langs = Locale.getISOLanguages();
for(String lang:langs)
{
      URL rb = ClassLoader.getSystemResource("widget_"+lang+".properties");
      if(rb!=null)
      {
            System.out.println("Found:"+rb.toString());
      }
}

推荐答案

我不认为有一个 API,因为可以动态创建新的有效语言环境对象:

I don't think there is an API for this because new valid locale objects can be created on the fly:

Locale locale = new Locale("abcd");

无需在某处注册.然后你可以使用资源包widget_abcd.properties 无限制:

without the need to register it somewhere. And then you can use a resource bundle widget_abcd.properties without restrictions:

ResourceBundle resource= ResourceBundle.getBundle("widget", new Locale("abcd"));

来自 java.util.Locale API 文档:

From the java.util.Locale API docs:

因为 Locale 对象只是一个区域的标识符,所以没有当你构建一个 Locale 时执行有效性检查.如果你想查看特定资源是否可用于您的语言环境构造,你必须查询那些资源.

Because a Locale object is just an identifier for a region, no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct, you must query those resources.

要解决这个问题,您仍然可以遍历资源目录中所有名为widget_"的文件并发现新添加的资源包.

To solve the problem you can still iterate over all files called "widget_" in the resource directory and discover the new added resource bundles.

请注意,由于上述原因,Locale.getAvailableLocales() 不是 100% 确定:您可能有一天会定义非标准语言环境.但是,如果您只添加几个标准语言环境,则可以使用此静态方法迭代系统语言环境并获取相应的包.

Note that Locale.getAvailableLocales() is not 100% sure for the above reason: you might some day define a non standard locale. But if you'll add only a few standard locales you can use this static method to iterate over the system locales and get the corresponding bundles.

相关文章