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.
1 Answer
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()... } }
ClassLoader#findResourcesto 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