Java : How to read data from properties file

How to read data from properties file


The Properties class represents a persistent or defined set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object.

The Properties file is highly used in automation. Let see with an example.

package com.qahumor;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class Reading_PropertyFile {

 /*
  * @author : Qahumor Reading Properties file in Java
  */

public static void main(String[] args) {

// Create an Object of Properties class.
Properties prop = new Properties();

// Get the path of properties file which you have created in your project.
// System.getProperty("user.dir") - help to read the root directory of your project.
// Change the below path accordingly.
String path = System.getProperty("user.dir") + "/src/config/test.properties";

// Print the path of file for Debug purpose
System.out.println("Debug : Properties file path :" + path);

try {

// Reading the File input stream
 FileInputStream fs = new FileInputStream(path);

// Load the file into memory
 prop.load(fs);
   
} catch (Exception e) {
 e.printStackTrace();
}

// Read the value from Property file - test.properties
System.out.println("\nVersion of the Property file is : " 
    + prop.getProperty("version"));

}

}

Output:

Version of the Property file is : 3.1.4




@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

To create a property file:
1. You can open a notepad
2. Type below content in it.
    version=3.1.4
    login=admin
    pswd=xxxx
3. Save it name "test.properties" in double quotes.
4. You can download the sample property file from Link


Thank you!!





No comments:

Post a Comment

Android : How to connect your Android device over Wifi using ADB command for App debugging

How to connect your Android device over Wi-Fi using ADB command Sometimes it requires to connect your Android dev...