4

I am trying to load a properties file directly from the resources directory of my Java project and am getting a null pointer exception. Can someone pl explain how to do it?

Code-

String resourceName = "config-values.properties"; 
Properties props = new Properties();
try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourceName)) {
            props.load(resourceStream);
        }

My folder structure is - /src/packageName and /src/resources/

3
  • Did you use maven to generate the project skeleton, if so can you confirm that you dir structure should be src/main/java AND src/main/resources. Otherwise, you may just need to use path as "resources/config-values.properties" in getResourceAsStream Commented Mar 14, 2017 at 6:50
  • Structure should be src/main/resources Commented Mar 14, 2017 at 6:51
  • The structure is not src/main/resources just src/resources @jatanp what do you mean by "need to use path as resources/config-values.properties"? Commented Mar 14, 2017 at 6:54

3 Answers 3

3

Adding another way to do it without stream

File ourFile = new File(getClass().getClassLoader().getResource("yourFile.txt").getFile());

and then you can do things like

ourFile.getAbsolutePath()
Sign up to request clarification or add additional context in comments.

Comments

2

Following code expects that the resource, you are trying to access, exists in your class path.

getClassLoader().getResourceAsStream(resourceName))

Assuming that your file exists in src/resources: You may add src/resources/ in your classpath. I don't know which IDE are you using but here are some ways to add a directory in the classpath:

Comments

1
InputStream resourceStream  = 
 getClass().getResourceAsStream("/package/folder/foo.properties");

Try above code.

Hope this will helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.