Reputation: 67
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/
Upvotes: 4
Views: 26056
Reputation: 2873
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()
Upvotes: 3
Reputation:
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:
Upvotes: 2
Reputation: 7937
InputStream resourceStream =
getClass().getResourceAsStream("/package/folder/foo.properties");
Try above code.
Hope this will helps.
Upvotes: 1