Loading Java Property Resource Files

Loading property resource files in Java is pretty straightforward, but the process can also kick your butt if you’re just starting out. Getting nothing but a null result when trying to read a property file is no fun at all. Hopefully something in this post will help you out if you’re in that situation.

Here is the basic rundown of reading a properties file as a File Input Stream. We’ll be reading files as Resource Streams a bit later.

Properties configProp = new Properties();
configProp.load(new FileInputStream(“projectroot.properties”));
System.out.println(“MySQL User: \t” + configProp.getProperty(“dbuser”));

Our project has several property files for our demo. They are located in theĀ project root, a location in our class path, our source root and package root.

Each of our property files is identical with the exception of a “filename” property that we will print out from each.

Here’s the source and the output.

A couple of things to point out.

1) We use a File Input Stream when the properties file is located in the project root. Using File Input Stream is also handy if we’re distributing a .JAR and want to include a properties file that’s user configurable.

Below is a console demo of a .JAR with a root config using the File Input Stream approach.

2) Reading a properties file with getResourceAsStream() is clean for the root of a class path or source root, but gets a little more demanding when adding from within the package where a relative path to the resource file is required.

One final tip is to make sure the Java Compiler supports the filename extension of the resource files you want to use. Here is where that is enabled in IntelliJ IDEA.

And above all, whatever you do, never EVER add an exclamation point before your properties file. The exclamation point means to EXCLUDE that file pattern. The exclamation will give you a null result when reading the resource file with getResourceAsStream() all the live long day.

Happy Resource Property Parsing!