I am trying to implement a method that when called, get a string from a particular resource in the jar that the class is loaded from.
import mypath.myclass; //from a jar String result = gitid.getGitId(myclass.class);
On the backed I am currently using:
InputStream is = null; BufferedReader br = null; String line; is = c.getResourceAsStream("/com/file.text");
The problem is I keep getting the same resource for no matter what class I give it.
I have also tried:
is = c.getClassLoader().getResourceAsStream("/com/file.text");
This fails completely.
Any suggestions would be much appreciated.
Also,what is the difference between calling getResourceAsStream from the class loader vs the class?
Class.getResourceAsStream() gets a
ClassLoader instance, pretty much the same you get from
What you could do, is get the URL for a given class and replace class resource path your path of your file. for example, the following code will return resource from the same jar:
Class c = String.class; URL u = c.getResource('/' + c.getName().replace('.', '/') + ".class"); String s = u.toString(); URL url = new URL(s.substring(0, s.indexOf('!')) + "!/META-INF/MANIFEST.MF"); InputStream is = url.openStream();
You'll have to handle not jarred class folders separately.
Probably all classes were loaded by the same ClassLoader instance. So as long as the path of the resource doesn't change you will get the same resource every time.
This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).