Reading and Writing Properties File in Java
The property file is a file we use in the Java Programming language to keep the configuration parameters. These files we called Resource Bundle because it is a bundle of resources that we are going to use in the application.
What are the configuration parameters?
Configuration parameters are the parameters that you use at the time of configuring your database, or any validation is there in the project you can add them as configuration parameters.
Example: You must have used DBConnect class for Database connection in your Java-based web application. We keep all the database URLs, database names, database drivers inside this class. Instead of writing this configuration parameter inside this class, we can create a system.properties file inside your resource folder of the java project. The extension we use for the properties file is .properties.
Let us see the properties files:
- Everything in the properties file is present in key-value pairs.
- So, in order to access any value from this file, we can use the key
Why we need a Properties file?
You can work without a properties file, but the advantage here is whenever you alter this file you don’t worry about the compilation.
Suppose you are creating a Java web-based project in that you are using some image path and that image path is used in different modules of your project. So, if you want to alter something in the path you have to change it in every module instead of what we can do, we can create a properties file in that we can have the parameters for the path of the image inside this. So, now we don’t need to alter every module. So, this is the advantage of using a properties file.
Here, we will create Our Normal JDBCMySqLConnection Class.java
This is the DBConnect.java file in the Java project. In this, we have used all the parameters inside this class, So, whenever your client wants to change the parameters he/she has to go to this file and have to change the things accordingly. But instead, what we can do here we can keep all these configuration parameters in the system.properties file.
Let us create a system.properties file in java.
Just right-click on your resources folder and create a property file.
Now, as you can see we have a property file where we kept all these parameters like URL, driver, username, and password of the database. We need to access this property file inside your Java class.
Let us see how we can access this file
We have to use the ResourceBundle class and Have to access using a key.
- First, we will create the object of the resource bundle and will pass the properties file name to it.
- Next, we have to use the getString(key) method to call the value.