简体   繁体   English

如何从文件而不是从jar加载资源束,具有相同的束基本名称

[英]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. 文件系统和jar中都有具有相同基本名称的资源包。 Try to load the resource bundle from file system, not from jar. 尝试从文件系统而不是从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. 该捆绑包是从jar而不是从文件系统加载的。 Why? 为什么? If I changed the bundle base name to my.foo.bundle(different from the bundle name in jar), it worked. 如果我将捆绑软件的基本名称更改为my.foo.bundle(与jar中的捆绑软件名称不同),则它可以正常工作。 But the bundle names are the same for file system and in jar. 但是对于文件系统和jar,捆绑包名称是相同的。 Is there a way? 有办法吗?

Thanks. 谢谢。

I believe that it is because of the way URLClassLoader loads resources. 我相信这是因为URLClassLoader加载资源的方式。

In case of URLClassLoader: 如果是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 1.使用构造函数

`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: 2.扩展URLClassLoader并重写getResource方法以从类加载器首先加载:


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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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