Search This Blog

Wednesday, November 21, 2018

Location of properties file in Java application

props = new Properties();

props.load(getClass().getClassLoader().getResourceAsStream("mail.properties"));

FileInputStream(..) in Java uses paths relative to the current user directory (see java.io.File documentation). So it looks for mail.properties in /home/usr/ or c:\documents and settings\usr. If your .properties file is on the application classpath you can read it throug the Class.getResourceAsStream(..) method.

Do NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));
to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")
And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")
will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/ca/i88/Test.properties")
will load a Test.properties file located in the package ca.i88.