0

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?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • @JonnyHenly Sorry, it was a typo. – St.Antario Nov 04 '16 at 21:48
  • 1
    The documentation for [`Class#getClassLoader`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getClassLoader--) explains why it would return `null`. – 4castle Nov 04 '16 at 21:53
  • can you run the command `tree` or equivalent on your project and add to question (curious where the resource file is relative to your class) – qwwqwwq Nov 04 '16 at 21:55

0 Answers0