I wrote the following simple program:
public class Test {
public static void main(String[] args) throws IOException {
System.out.println(get(Test.class.getResource("/c.conf"))); //fine
System.out.println(
get(Test.class.getClassLoader().getResource("/c.conf"))
); //NPE, Test.class.getClassLoader().getResource("/c.conf") returns null
}
public static String get(URL url) throws IOException {
InputStreamReader reader = new InputStreamReader(url.openStream());
StringBuilder sb = new StringBuilder();
int current;
while ((current = reader.read()) != -1)
sb.append((char) current);
return sb.toString();
}
}
So, I looked at the documentation of Class::getResource(String)
and found this:
The rules for searching resources associated with a given class are implemented by the defining class loader of the class.
So I thought these two methods should have loaded the resource in the same way.
Why does Test.class.getClassLoader().getResource("/c.conf")
throw NullPointerException
whereas Test.class.getResource("/c.conf")
does not?