Java Properties File – How to Read and Write

In this tutorial you will learn about java properties file and how to perform read and write operations on it.

 

What is properties file?

In Java related technologies, properties file is used to store configuration data or settings of application. It has .properties extension.

 

Why we need properties file?

It makes application maintenance easier. We can change some information in application by doing changes in properties file. We don’t need to recompile the java source files.

Let us consider a real life example where properties file is really helpful.

You have developed an application that uses database. The application will use some information like username and password to connect with database installed on your system. After some days if you change the username and password of database on system. Now the application can’t connect with database as it is using the old username and password.

The solution to this problem is to save the database details in properties file. Where ever you require database details just access it from this file. Now if you want some changes in details then you just have to do change in properties file and the change is reflected in entire application.

So, we can say that properties file contains variables information that may change in future.

 

Properties Class in Java

Properties class is used to save information in the form of key and value pair. It is subclass of Hashtable class.

It is used to perform read and write operations on properties file. We can save information in properties file in text or XML format.

 

Java Properties File Example

How to read from properties file?

First of all create a file with .properties extension and add some information in it.

For example I have created a file and added following information in it.

 

demo.properties

name=neeraj

age=22

 

Below example shows that how to read this file

 

Output

neeraj

22

 

How to write to properties file?

In this example we will write some information in demo.properties file.

 

After executing this program the file will contain following information

demo.properties

Java Properties File – How to Read and Write

 

You can ask your queries in comment section if you have any doubt regarding above java properties file tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *