How getClassLoader().getResourceAsStream() works in java

I google how below code loads the resource Abc.class.getClassLoader().getResourceAsStream("abc.txt") and find that it searchs the resource in all jar file and zip file in class path.

Thats correct when you work only with a single ClassLoader (most non-OSGi/ non-modular environments). Then all content of all JARs can be seen as one big tree, where classes and resources of JARs, which occur prior in the class path, win over those of JARS, which occur further behind.

But when i tried it I am not able to loads it but if i give package path then I am able to loads it can someone tell me how getResourceAsStream search the class path

Abc.class.getClassLoader().getResourceAsStream("abc.txt")

searches at root of the tree while:

Abc.class.getResourceAsStream("abc.txt")

searches relative to the package of Abc.

Abc.class.getResourceAsStream("/abc.txt")

searches at the root of the tree again.

All these methode will only search in the specified directory (or the root directory) and won't traverse and search the whole tree.

Personally, I usually always use the latter two versions (Class.getResourceAsStream) and rarely use the ClassLoader.getResourceAsStream method directly.


For example, you can make a "resources" source folder, put files in it, then use Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.txt");
I always use this method.

Tags:

Java

Core