Like getClassLoader (). GetResourceAsStream () works in java

I google how below code is loading Abc.class.getClassLoader () resource. GetResourceAsStream ("abc.txt")
and find that it looks for the resource in all jar and zip files in the classpath.

But when i tried i cant load it but if i give package path then i can load it can someone tell me how getResourceAsStream looks for classpath

thank

one scenario: - My below code is a simple program and the abc.txt resource file is inside the com.abc package. when I give the path to the package it worked and when I didn't, it doesn't work.

package com.abc;

public class ResourceExp {

    public static void main(String args[])
    {
        new ResourceExp().getResource();
    }

    public void getResource()
    {
        String name = "abc.txt";
        // worked
        System.out.println(ResourceExp.class.getClassLoader().getResourceAsStream("com/abc/"+name));
        //not workded
        //System.out.println(ResourceExp.class.getClassLoader().getResourceAsStream(name));

    }

}    

      

if getResourceAsStream is looking at resource in all jar files and directory then why should I give the package path

+3


source to share


2 answers


I google how below code is loading Abc.class.getClassLoader () resource. GetResourceAsStream ("abc.txt") and find that it looks for the resource in all jar and zip files in the class path.

This is correct when you are only working with one ClassLoader (most non-OSGi / non-modular environments). The entire content of all JARs can then be thought of as one big tree, where classes and JAR resources that occur earlier in the classpath outperform those from JARS that occur further.

But when I tried I can not load it, but if I give the package the path then I can load it, can someone tell me how getResourceAsStream looks for the classpath

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

      

searches at the root of the tree, and:

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

      



performs a search over the Abc package.

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

      

looking again at the root of the tree.

All of these methods will only search in the specified directory (or root directory) and will not navigate and search the entire tree.

Personally, I usually use the last two versions ( Class.getResourceAsStream

) and rarely use the ClassLoader.getResourceAsStream

.

+5


source


For example, you can create a source folder "Resources" , put files in it, and then use Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.txt");


I always use this method.



0


source







All Articles