有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中ResourceBundle的io查询

直接从这个API

Otherwise, getBundle attempts to locate a property resource file using the generated properties file name. It generates a path name from the candidate bundle name by replacing all "." characters with "/" and appending the string ".properties". It attempts to find a "resource" with this name using ClassLoader.getResource.

它们对replacing all "." characters with "/"意味着什么?举个例子吧? 附言:我同意追加。属性


共 (1) 个答案

  1. # 1 楼答案

    假设您有一个名为

    com.yourgroup.bundles
    

    包含名为

    hello_en_US.properties
    

    您必须指定以下任一项才能加载捆绑包

    ResourceBundle bundle = ResourceBundle.getBundle("com.yourgroup.bundles.hello");
    ResourceBundle bundle = ResourceBundle.getBundle("com/yourgroup/bundles/hello");
    

    基本上,javadoc告诉您如何将传递给getBundle方法的参数转换为类路径上的资源。对我来说,默认的语言环境是en_US,所以

    com.yourgroup.bundles.hello
    

    转化为

    com/yourgroup/bundles/hello_en_US.properties
    

    然后,它可以使用ClassLoader来查找该资源

    如果正确映射其名称,它返回的ResourceBundle实现实际上可能是一个自定义类。按照javadoc进行操作。否则,它只是一个Properties资源包

    魔法发生在ResourceBundle#newBundle(...)

    String bundleName = toBundleName(baseName, locale); // baseName being 'com.yourgroup.bundles.hello' in my example above
    ...
    final String resourceName = toResourceName(bundleName, "properties");
    

    这很简单

    public final String toResourceName(String bundleName, String suffix) {
        StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
        sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
        return sb.toString();
    }
    
    ....
    
    URL url = classLoader.getResource(resourceName);
    ...
    bundle = new PropertyResourceBundle(stream); // stream comes from url