tags:

views:

313

answers:

4

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  A: 

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.

Dave Ray
A: 

It works much the same way as for finding class files. So first try the parent class loader (recursively) then do whatever the class loader implementation does to find files.

There is no checking of the immediate caller class loader (as ResourceBundle does - see section 6.3 of the Java Secure Coding Guidelines). However, you do need permissions to open the URL, as ClassLoader.getResourceAsStream just calls URL.openStream in the default implementation.

Tom Hawtin - tackline
A: 

Specify the package. Assuming you use com.yourcompany.file it SHOULD be unique. (Unless someone WANTS to override your config file via the classpath.)

Chris Nava
A: 

If you want to read the file only from a specific JAR you can open the JarFile and read it directly.

Peter Lawrey