Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

core - 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.

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

Thanks

one scenario is :- My below code is a simple program and my resource file abc.txt is inside com.abc package. when i specify path of package it worked and when i did not it does not 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 looks the resource in all jar file and directory then why i have to specify the package path

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...