Giardino
Giardino

Reputation: 1387

Issue when trying to use getResourceAsStream in java

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?

Upvotes: 2

Views: 550

Answers (3)

thewaterwalker
thewaterwalker

Reputation: 324

That should be

getResourceAsStream("qbooksprintfix/resources/config");

or preferably

Thread.currentThread().getContextClassLoader().getResourceAsStream("qbooksprintfix/resources/config");

Upvotes: 0

John Farrelly
John Farrelly

Reputation: 7459

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");

Upvotes: 0

c.s.
c.s.

Reputation: 4816

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")

Upvotes: 4

Related Questions