AP01
AP01

Reputation: 67

How to load file from resources directory in Java

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

Answers (3)

HRVHackers
HRVHackers

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

user2241537
user2241537

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

Sagar Gangwal
Sagar Gangwal

Reputation: 7937

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

Try above code.

Hope this will helps.

Upvotes: 1

Related Questions