2

So basically I have two lines in my code that are as follows:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/config");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

and my file structure in eclipse is as follows (image posted):

enter image description here

When I try to run this code, I get NullPointerExceptions when it reaches the second line (BufferedReader line). I can't for the life of me figure out why InputStream "is" is becoming null. Any ideas?

Giardino
  • 1,367
  • 3
  • 10
  • 30
  • 2
    Try `getResourceAsStream("qbooksprintfix/resources/config")`. More details [here](http://stackoverflow.com/a/18280628/2581401) – c.s. Aug 19 '13 at 19:53
  • @c.s. Duh, that worked! – Giardino Aug 19 '13 at 19:57
  • 1
    @AndyThomas: the path is relative to the package of the class whan Class.getResourceAsStream is used, but not when ClassLoader.getResourceAsStream() is used. In the latter case, the path is always absolute. – JB Nizet Aug 19 '13 at 20:00
  • @JBNizet - Thanks for the correction. I saw *getResourceAsStream()* and totally overlooked the preceding *getClassLoader()*. – Andy Thomas Aug 19 '13 at 20:26

3 Answers3

4

When you are using a classloader to load a stream, the path you are using is always an absolute path (so you should not use a leading / in this case) and should start with your root package. In your case this is under src.

So since your resource is under package qbooksprintfix/resources you should access it like:

getResourceAsStream("qbooksprintfix/resources/config")

c.s.
  • 4,786
  • 18
  • 32
0

getResourceAsStream() looks in the classpath for the item, so the "base" directory for it in your case is probably src:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("qbooksprintfix/resources/config");
John Farrelly
  • 7,289
  • 9
  • 42
  • 52
  • 1
    When using a classloader's `getResourceAsStream()` all paths are absolute so you should not use a starting `/` – c.s. Aug 19 '13 at 20:02
  • @c.s. Ah! I generally do `getResourceAsStream()` from `Class` rather than `ClassLoader` so didn't know there was a difference! – John Farrelly Aug 19 '13 at 20:07
  • Yes that's their main difference. Please fix your answer so I remove my downvote – c.s. Aug 19 '13 at 20:10
0

That should be

getResourceAsStream("qbooksprintfix/resources/config");

or preferably

Thread.currentThread().getContextClassLoader().getResourceAsStream("qbooksprintfix/resources/config");
thewaterwalker
  • 322
  • 2
  • 11