.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:
1 2 |
env=DEV huongdanjava.base.url=https://huongdanjava.com |
To work with .properties files in Java, we can use objects of the Properties class:
1 |
Properties properties = new Properties(); |
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:
1 2 |
Path path = Paths.get("src", "main", "resources", "config.properties"); InputStream inputStream = new FileInputStream(path.toFile()); |
Now I can read the content of the config.properties file using the load() method as follows:
1 |
properties.load(inputStream); |
After reading, you can get information about the properties in this file using the getProperty() method of the Properties object, for example as follows:
1 |
System.out.println(properties.getProperty("env")); |
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:
1 |
System.out.println(properties.getProperty("test", "Testing")); |
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:
1 2 3 4 5 |
properties.setProperty("test", "Testing"); properties.setProperty("env", "PROD"); System.out.println(properties.getProperty("test")); System.out.println(properties.getProperty("env")); |
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:
1 2 3 |
properties.remove("env"); System.out.println(properties.getProperty("env")); |
The result will be as follows: