This post will discuss how to read properties files in Java.

A properties file consists of key-value pairs of string types that can have any extension, although .properties is recommended to distinguish them from other files easily.

We can read properties files in Java using the Properties class. The Properties class represents a persistent set of properties that can be loaded from a stream using its load() method.

1. Using ClassLoader

The class loader is responsible for loading classes and resources. We can use the ClassLoader class to load the properties file from the classpath in a static context, as shown below:

Download Code

 
Every Class object contains a reference to the ClassLoader that defined it. In a non-static context, we can do something like the following to load the properties file from the classpath using the ClassLoader class.

Download Code

 
If our resource exists on the file system rather than on the classpath, we can use the static method getSystemResourceAsStream() of the ClassLoader class, which returns an InputStream for reading the resource.

Download Code

2. Using Class

We can use getResourceAsStream() method of the Class object instead of ClassLoader class. This method delegates to this object’s class loader.

Download Code

3. Using FileInputStream

If your properties file exists on the file system rather than on classpath, we can use FileInputStream to get an InputStream, as shown below:

Download Code

4. Using Apache Commons Configuration

We can even read properties file using third-party libraries like Apache Commons Configuration. Here’s a working example:

Download Code

5. Using ResourceBundle

Finally, we can use the ResourceBundle class to read the properties file, as shown below:

Download Code

 
We can also load the properties files into a FileInputStream, and then use a PropertyResourceBundle to get ResourceBundle instance, as demonstrated below:

Download Code

That’s all about reading property files in Java.