在Java中,我如何找到我的Resource Bundle可用的语言 [英] In Java how do I find out what languages I have available my Resource Bundle

查看:401
本文介绍了在Java中,我如何找到我的Resource Bundle可用的语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主jar包装了一些资源包

I have some resource bundles packaged in my main jar

widget_en.properties
widget_de.properties

我根据我的默认语言环境检索资源包作为folows

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我只使用不同语言的资源包(我没有国家/地区改进)所以我通过迭代所有已知的语言代码生成了一个列表,并检查每个语言代码作为资源。

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 docs:

From the java.util.Locale API docs:


因为Locale对象只是区域的标识符,所以在构造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.

请注意<$ c由于上述原因,$ c> 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.

这篇关于在Java中,我如何找到我的Resource Bundle可用的语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆