user1745356
user1745356

Reputation: 4673

How to get a resource from a specific jar

I have a few jars which contain some resources with the same name. Lets say I have a.jar and b.jar and they both contain resource.xml. I know I can get a resource calling

getClass().getClassLoader().getResourceAsStream("resource.xml");

But AFAIK it may return a resource either from a.jar or b.jar. I want to pass the jar file name and get the resources from the specified jar.

Upvotes: 4

Views: 717

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

Make sure that a.jar is before b.jar on the classpath.

If you cannot guarantee that you can do something like this

    ...
    Enumeration<URL> urls = getClass().getClassLoader().getResources("resource.xml");
    while(urls.hasMoreElements()) {
        URL url = urls.nextElement();
        if (url.getPath().contains("/a.jar")) {
            return url;
        }
    }
    return null;

Upvotes: 3

Juanjo Vega
Juanjo Vega

Reputation: 1430

If they are in different packages (check your jars manifest) you can use packagename to access R class.

As an example:

getResources().getString(<com.mycompany.mypackage>.R.string.yourstring)

Upvotes: -1

Related Questions