Roufid

Read properties file in Java

Java properties file - Radouane Roufid

Properties file are often used in Java applications in the aim to store configuration parameters, internationalization and various informations. A properties file have « .properties »  as extension where each line is a key/value entry. The key and the value are separated by the equal symbol « = ». Properties can also be stored in a XML file (see last chapter).

In this tutorial, we will see how to read a properties file in Java. Consider the following properties file named config.properties :

1- Load properties file

Since JDK 1.0

Java offers the Properties class from the java.util package to read properties file. Below an example :

Note that we used the With a try with resources, so no need to close the inputStream.

Output :

2- Load properties from a file located in classpath

The access to a properties file located in application classpath depends of whether your are on a static method or not.

In a static method, you can access a file in your classpath by using the following code :

Full example :

In a non-static method, you can access a file in the classpath by using the following code :

3- XML properties file

Properties can also be stored in a XML file respecting the properties dtd. Below an example  :

However, reading the properties file remains the same. Replace just

by