First, getResourceAsStream method
The getResourceAsStream method is implemented as follows:
Public InputStream getResourceAsStream (String name) { = getresource (name); Try { returnnullnull; Catch (IOException e) { returnnull; } }
The GetResource method is called in the visible getResourceAsStream method to find the specified resource.
Then look at the source code of GetResource:
Public URL getresource (String name) { URL url; if (parent! = null) { URL = parent.getresource (name); } else { url = getbootstrapresource (name); } if (url = = null) { URL = findresource (name); } return URL; }
Because Bootstrap is the top-level ClassLoader, the parent that defines it in Java is null.
This first determines whether the parent is null, and if the parent is not NULL, the ClassLoader of this class is not boostrap.
In addition, by Parent.getresource (name), this sentence finds that ClassLoader will always invoke the GetResource method of its parent class, which is consistent with the ClassLoader parent class loading mechanism.
In other words, when reading a resource file, the search order of the directory is
Jre/lib/rt.jar Note that the search is within the contents of the jar package, and the siblings outside the jar package are not in the search scope
Jre/lib/ext/*.jar
Classpath Directory
Also, if the parent path and the downlevel path have resources to be searched at the same time, the resource under the ancestor path will be the search result.
Example:
InputStream in = QuickStart.class.getClassLoader (). getResourceAsStream ("Haha.txt"); InputStreamReader ISR = new InputStreamReader (in); BufferedReader BR =new BufferedReader (ISR); String s = null;while (null! = (s = br.readline ())) {System.out.println (s);}
For multithreaded notation, read in the following thread context:
InputStream in = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Haha.txt");
Java ClassLoader Two reads a resource file through the ClassLoader