Java receives a file as a resource when it is in the project folder

I currently have a project in Java configured 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, InputStream is always null, which crashes when it hits the second line. I know that this has something to do with how I set up the path he is looking for, but I cannot understand exactly why it is not working.

+6
source share
2 answers

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

However, Eclipse does not put it in the classpath. To make it be on the path to the class, right-click your folder and add it as the source folder. Then Eclipse will add it to the root of the class path. You can get it with

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

Eclipse places everything in the source resources folder, starting at the root of the class path. therefore

resources/config

appears in the class path as

 /config /qbooksprintfix/FileChecker /qbooksprintfxi/FilePurgeHandler /... 
+9
source

Try using InputStream is = this.getClass().getClassLoader().getResource("/resources/config").openStream();

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

In both cases, do not forget to put "/" before "resources"

0
source

Source: https://habr.com/ru/post/952298/


All Articles