简体   繁体   中英

How to load resource bundle from file, not from jar, same bundle base name

There are resource bundles with the same base name in both file system and jar. Try to load the resource bundle from file system, not from jar.

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{filePathURL});
ResourceBundle bundle = ResourceBundle.getBundle( "my.bundle", locale, urlLoader );

The bundle is loaded from jar, not from the file system. Why? If I changed the bundle base name to my.foo.bundle(different from the bundle name in jar), it worked. But the bundle names are the same for file system and in jar. Is there a way?

Thanks.

I believe that it is because of the way URLClassLoader loads resources.

In case of URLClassLoader:
Whenever a resource is requested, it first asks the parent class-loader to load it. If that resource is not available it then checks the child class loaders.


Not sure whether this is the best way but, possible solutions:

1. Use the constructor

`public URLClassLoader(URL[] urls, ClassLoader parent)`

And give null for parent

Like so:

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{filePathURL}, null);
ResourceBundle bundle = ResourceBundle.getBundle( "my.bundle", locale, urlLoader );

2. Extend the URLClassLoader and override the method getResource method to load from your class loader first:


public URL getResource(String name) {
    URL url = findResource(name); // this will load from your class loader
    if (url == null) {
        if (parent != null) {
            url = parent.getResource(name);
        } else {
            url = getBootstrapResource(name);
        }
    }

    return url;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM