I\'m loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:
/src/initialization/Life
The default JVM classloader will use parent-classloader to load resources first: .
Lifepaths.class.getClass()
's classloader is bootstrap classloader
, so getResourceAsStream
will search $JAVA_HOME only, regardless of user provided classpath
. Obviously, Lifepaths.txt is not there.
Lifepaths.class
's classloader is system classpath classloader
, so getResourceAsStream
will search user-defined classpath
and Lifepaths.txt is there.
When using java.lang.Class#getResourceAsStream(String name)
, name which is not start with '/' will be added with package name
as prefix. If you want avoid this, please using java.lang.ClassLoader#getResourceAsStream
.
For example:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String resourceName = "Lifepaths.txt";
InputStream resourceStream = loader.getResourceAsStream(resourceName);