2

Let's say you have jar1 with artifactId zoo, and jar2 with artifactId animals. Both jars have a resource file with the same path (ex: /animals/animal.txt). Is there any way to read that file from a specific jar? Using getResourcesAsStream also returns the first jar but sometimes I want the second jar's animal.txt file.

2
  • The first question which comes to my mind is: Why do you need to read a resource from another JAR ? And using your own ? Furthermore the order in which you read depends on the classpath which is usually not predictable...apart from that it sounds strange having two different jars which contain the same resource including the same path etc. ? Commented Feb 20, 2018 at 19:22
  • 1
    The short answer is no. In fact, this is actually a really neat trick which can be used to generate plugin style frameworks or no coupled API functionality. You can use ClassLoader#findResources to list all the named resources, within the class loaders context, and load them, allowing you to dynamically locate runtime resources. As to your actual problem. Either change the names of the resource files OR place a entry marker in the file to allow you to identify which file it actually is Commented Feb 20, 2018 at 19:46

1 Answer 1

1

As @MadProgrammer suggests, ClassLoader.getResources() will return URLs, which look like jar:file:/C:/dir/animals.jar!/animals/animal.txt.

So this sort of excerpt should be able to choose the right file:

 Enumeration<URL> urls = getClass().getClassLoader().getResources("/animals/animal.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (url.toExternalForm().contains("animals.jar!")) { System.out.println(url); url.openStream()... } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.