2

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/

AP01
  • 47
  • 1
  • 2
  • 9
  • 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 – jatanp Mar 14 '17 at 06:50
  • Structure should be src/main/resources – imprezzeb Mar 14 '17 at 06: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"? – AP01 Mar 14 '17 at 06:54

3 Answers3

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:

Community
  • 1
  • 1
2

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()
HRVHackers
  • 2,793
  • 4
  • 36
  • 38
1
InputStream resourceStream  = 
 getClass().getResourceAsStream("/package/folder/foo.properties");

Try above code.

Hope this will helps.

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38