Question

Directly from this 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.

What do they mean with replacing all "." characters with "/" What would be an example? PS:I am ok with appending .properties at the end.

Était-ce utile?

La solution

Say you have a package named

com.yourgroup.bundles

containing a file named

hello_en_US.properties

you would have to specify either of the following to load a bundle

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

Basically the javadoc is telling you how it translates the argument you pass to the getBundle method to find the resource on your classpath. For me, the default Locale is en_US, so

com.yourgroup.bundles.hello

translates to

com/yourgroup/bundles/hello_en_US.properties

It can then use the ClassLoader to find that resource.

The ResourceBundle implementation it returns might actually be a custom class, if you map its name correctly. Follow the javadoc for that. Otherwise, it's just a Properties resource bundle.

The magic happens in ResourceBundle#newBundle(...)

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

and that is simply

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top