【问题标题】:resource bundle java资源包java
【发布时间】:2011-05-31 14:12:32
【问题描述】:

是否可以在类似于以下的文件夹结构中维护资源包;

 1. us\en
 2. ae\en
 3. ae\ar

资源包文件名相同,但保存在不同的文件夹中。我知道 Java 推荐

myresource_en_US.properties

但我需要将它们保存在文件夹中并使用资源包类进行访问。我正在使用 JDK 6。有人知道我该怎么做吗?

【问题讨论】:

    标签: java resourcebundle


    【解决方案1】:

    是的,您可以使用自定义 Control 控制加载。这是一个启动示例:

    public class FolderControl extends Control {
        public ResourceBundle newBundle
            (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                throws IllegalAccessException, InstantiationException, IOException
        {
            String resourceName = "/" + locale.getCountry() + "/" + locale.getLanguage() 
                + "/" baseName + ".properties";
            ResourceBundle bundle = null;
            InputStream stream = null;
            if (reload) {
                URL url = loader.getResource(resourceName);
                if (url != null) {
                    URLConnection connection = url.openConnection();
                    if (connection != null) {
                        connection.setUseCaches(false);
                        stream = connection.getInputStream();
                    }
                }
            } else {
                stream = loader.getResourceAsStream(resourceName);
            }
            if (stream != null) {
                try {
                    bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
                } finally {
                    stream.close();
                }
            }
            return bundle;
        }
    }
    

    (源代码是从默认实现复制的,仅更改了 resourceName 和更改了 PropertyResourceBundle 以将流读取为 UTF-8 -- 不再需要 native2ascii)

    你使用如下

    ResourceBundle bundle = ResourceBundle.getBundle("myresource", new FolderControl());
    // ...
    

    另见:

    【讨论】:

      【解决方案2】:

      看看http://download.oracle.com/javase/6/docs/api/java/util/ResourceBundle.Control.html。您可以将一个作为参数传递给ResourceBundle.getBundle(),作为“在本地化资源的组织和打包中提供不同约定”的一种方式。

      【讨论】:

        猜你喜欢
        • 2011-02-07
        • 2010-11-13
        • 2020-04-26
        • 2020-10-03
        • 1970-01-01
        • 2017-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多