Properties Class in Java

Price: INR 1,299.00
Was: INR 1,799.00

Let’s learn about the Properties Class in Java.  Normally, Java properties file is used to store project configuration data or settings. The properties object contains key-value pair both as a string. It is the subclass of Hashtable.

The Properties class provides methods to get data from the properties file and store data into the properties file. It can be used to get property value based on the property key.

 

Write Properties File in Java

In this tutorial we will see, How can we write into the Properties file like config.properties. Suppose we need to write our project DB details in the properties file. First, we need to create the properties file. We will create the properties file with name config.properties and write the properties into it.

You can create the properties file using above example. You can copy it on your local machine and run the program. It will create the properties file named config.properties inside your project directory. You need to refresh your project to see the properties file in your Eclipse project structure. The properties file content will be.

Output:

#Thu Dec 24 18:35:24 IST 2015
dbpassword=Selenium
database=localhost
dbuser=Seleniumbix

 

Load Properties File in Java

In the last example, we have seen, How to write in the properties file. Now we will see how can we read from properties file before reading from the properties file, We need to load the properties file first. Let’s understand this with an easy example –

Output:

localhost
Seleniumbix
Selenium

 

You can see, We read the values from the properties file on the basis of the keys.

So this is the way, How can we write and read from the properties file in Java.

Methods of the Properties File

Now let’s see some methods of the Properties class. Although we have seen many of those in previous examples-

  1. getProperty(String key) – Retrieves the property with the specified key in this property list.
  2. load(InputStream inStream) – loads data from the InputStream object.
  3. load(Reader reader) – loads data from the Reader object.
  4. setProperty(String key, String value) – Calls the Hashtable method put, so as to set the specified value to the specified key.
  5. store(OutputStream out, String comments) – Writes this property list (key/value pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table (when using the load(InputStream in) method).
  6. stringPropertyNames() – Returns a set of keys which also includes all those distinct keys in the default property list that have a key with a name that has not been found in the main properties list.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply