Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.getResourceAsStream() issue

Tags:

java

I have a JAR-archive with java classes. One of them uses some resource that is embedded into the same JAR. In order to load that resource I use

MyClass.class.getResourceAsStream(myResourceName);

One thing that bothers me though is whether it is guaranteed that required resource will be loaded from within the same JAR. The documentation for "getResourceAsStream()" method (and corresponding ClassLoader's method) is not really clear to me.

What would happen if there's a resource with the same name located somewhere in JVM classpath before my JAR? Will that resource be loaded instead of the one embedded in my JAR? Is there any other way to substitute resource embedded in JAR?


1 Answers

Yes. The first matching resource found on the class path is returned, just like an executable search path. This is why resources are often "namespaced" by putting them in directories that mirror the package structure of the library or application.

This behavior may be slightly different in the presence of custom classloaders (say in OSGi), but for vanilla Java apps, it is the case.

like image 106
Dave Ray Avatar answered Nov 26 '25 20:11

Dave Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!