Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load file from resources directory in Java

Tags:

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/

like image 857
AP01 Avatar asked Oct 30 '25 20:10

AP01


1 Answers

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()
like image 189
HRVHackers Avatar answered Nov 02 '25 11:11

HRVHackers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!