Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getting file as resource when it's in the project folder

Tags:

java

io

I currently have a project in Java set up with the following directory structure in Eclipse:

enter image description here

And in my code I have the following lines:

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

However, the InputStream is always gets assigned to null, which causes a crash when it gets to the second line. I know it has something to do with how I set up the path that it's looking for, but I can't figure out exactly why it isn't working.

like image 902
Giardino Avatar asked Aug 22 '13 16:08

Giardino


1 Answers

Your config file is in your project, somewhere on the file system.

However, Eclipse isn't putting it on the classpath. To force it to be on the classpath, right click your folder and add it as a source folder. Eclipse will then add it to the root of the classpath. You can retrieve it with

InputStream is = this.getClass().getResourceAsStream("/config");

Eclipse puts everything in resources source folder starting at the root of the classpath. Therefore

resources/config

will appear in classpath as

/config
/qbooksprintfix/FileChecker
/qbooksprintfxi/FilePurgeHandler
/...
like image 110
Sotirios Delimanolis Avatar answered Oct 22 '22 23:10

Sotirios Delimanolis