artaxerxe artaxerxe - 2 years ago 105
Java Question

Cannot load properties file from resources directory

I imported a project from a Git repository and added Maven nature to it in Eclipse. In the resources folder, I added a configuration file called
. Now, whenever I try to open this file from my Java code, I get
. The file is also present in the
folder generated after maven compiles the project.

Can anyone tell me what can be the problem? My Java code that tries to load this file is:

props.load(new FileInputStream(""));

is a

Can anyone give me some hints on how to solve this issue?

Answer Source

If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.

The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:

String resourceName = ""; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
// use props here ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download