Working with .properties files using the Properties class in Java

.properties files are files used to configure information for the application. This is information that can change during the process of developing and deploying the application to the production environment. This information will be defined with key and value pairs in the .properties file, for example as follows:

To work with .properties files in Java, we can use objects of the Properties class:

You can use the load() methods of this Properties object with a parameter that can be a Reader or an InputStream to read the content of the .properties file.

For example, my config.properties file with the above content is in the project’s src/main/resources folder:

To read the content of this config.properties file, I will define an InputStream as follows:

Now I can read the content of the config.properties file using the load() method as follows:

After reading, you can get information about the properties in this file using the getProperty() method of the Properties object, for example as follows:

Result:

You can assign a default value in case the property we are looking for is not available, using the getProperty() method with 2 parameters: property name and default value, for example as follows:

In the config.properties file, there is no “test” property, so if I run this example again, you will see the default value returned as follows:

You can also add and modify the value of properties after reading the .properties file using the setProperty() method, for example as follows:

In the example above, I added a new property “test” and updated the value of the property “env”. Now run the example, you can see the following results:

Although the value of the “env” property in the config.properties file is “DEV”, the value of this property is now “PROD”!

You can also remove the property if you want, for example as follows:

The result will be as follows:

Add Comment