Properties files

Properties files stores simple parameters as key-value pairs, outside of compiled code. Key and Values are separated using '=' sign

Most of the time properties file used to store url, username, password, environment etc..

Eg:

Key=Value
Desert=hot


Rules about properties files

  1. Entries are generally expected to be a single line of the form, one of the following:
  2. Output :
    propertyName=propertyValue
    
    propertyName:propertyValue
    

  3. White space that appears between the property name and property value is ignored, so the following are equivalent.
  4. Output :
    name=cherchertech
    name = cherchertech
    

    White space at the beginning of the line is also ignored.

  5. Lines that start with the comment characters ! or # are ignored. Blank lines are also ignored.
  6. The property value is generally terminated by the end of the line. White space following the property value is not ignored, and is treated as part of the property value.
  7. A property value can span several lines if each line is terminated by a backslash ('\') character. For example:
  8. Output :
    targetCities=\
            Detroit,\
            Chicago,\
            Los Angeles
    

    This is equivalent to targetCities=Detroit,Chicago,Los Angeles (white space at the beginning of lines is ignored).

  9. The characters newline, carriage return, and tab can be inserted with characters \n, \r, and \t, respectively.
  10. The backslash character must be escaped as a double backslash. For example: path=c:\\docs\\doc1
  11. UNICODE characters can be entered as they are in a Java program, using the \u prefix. For example, \u002c.

Read Properties File

We can read and write the properties file in selenium using the Properties class present in the Java, this class provide few methods to read and write the data into properties file.

Insights about properties files

  • You can store the file anywhere in local file system, better if you can place it relative to you project
  • Recommended .properties extension however you can choose your own extension like text so on.
  • Properties class extends Hash table, you can iterate over the values in properties file like you would in a Hashtable.

Follow below steps to read property file
1. Create a Java class on Eclipse
read-properties-file-in-java-selenium

2. Create a properties file on your local machine with .properties extension. properties-file-java-selenium

3. Create Object for FileInputStream with .properties file path, it makes the file into stream of input item

// create file input stream object for the properties file
FileInputStream fis = new FileInputStream("C:\\path\\config.properties");


4. Create Properties class object to access the property file.

// create object for Properties class
Properties prop = new Properties();


5. Load the property file using load() present in the Properties object

// Load properties file
prop.load(fis);


6. Get the values using 'get("key")' method or getProperty("key") method by passing key as the patrameter

prop.getProperty("author");
prop.get("user");


Complete Program to Read value from properties file with java


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

public class ReadProperties {
	public static void main(String[] args) throws IOException {
		// create file input stream object for the properties file
		FileInputStream fis = new FileInputStream("C:\\path\\config.properties");
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		prop.load(fis);
		// get the property of "url" using getProperty()
		System.out.println(prop.getProperty("url"));
		System.out.println(prop.getProperty("author"));
		// get the property of "url" using get()
		System.out.println(prop.get("user"));
	}
}

Output :
		https://chercher.tech
		unknown
		any one in the world

HtmlUnitDriver for headless execution in Selenium webdriver

Read Properties file from ClassPath

To read files from the class path, we have to give the relative path to the file. We can retrieve the class path using this.getClass().getResourceAsStream()

All the steps will remain same except the path of the file


										// create file input stream object for the properties file
										FileInputStream fis = new FileInputStream(this.getClass().getResourceAsStream("/test.properties"));
										// create Properties class object to access properties file
										Properties prop = new Properties();
										

Properties files in text format

Sometimes properties could be in different format like '.txt' or other extension, file could have any extension still we can use the same methods what we used in .properties file.

config file config-p-text-properties-file-java-selenium

This program shows how to read Properties files in text format


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

public class PropertiesTextExtension {
	public static void main(String[] args) throws IOException {
		// create file input stream object for the properties file
		FileInputStream fis = new FileInputStream("C:\\path\\config-p.txt");
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		prop.load(fis);
		// get the property of "url" using getProperty()
		System.out.println(prop.getProperty("time"));
		// get the property of "url" using get()
		System.out.println(prop.get("hour"));
	}
}
						

Output :
output-of-text-properties-file

Read QR by taking as Screenshot in Selenium

Write Properties File

Follow below steps to write property file
1. Create a Java class on Eclipse
write-properties-file-in-java-selenium

2. Create a properties file on your local machine with .properties extension(config-write.properties). write-properties-file-java-selenium

3. Create Object for FileOutputStream with .properties file path, it makes the file into stream of output item

// create file output stream object for the properties file
FileOutputStream fos = new FileOutputStream("C:\\path\\config-write.properties");
		


4. Create Properties class object to access the property file.

// create object for Properties class
Properties prop = new Properties();


5. Set the values using getProperty("key","Value") method by passing key and values as the parameters

// set the properties
prop.setProperty("Selenium", "https://chercher.tech");


6. Store the values onto file commit it to local file system using prop.store(fos)

// set the properties
prop.setProperty("Selenium", "https://chercher.tech");


7. It will store the values along with the committed time on the first line


Complete Program to Write values to properties file with java


import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WriteProperties {
	public static void main(String[] args) throws IOException {
		// create file output stream object for the properties file
		FileOutputStream fis = new FileOutputStream("C:\\path\\config-write.properties");
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		// set the properties
		prop.setProperty("Selenium", "https://chercher.tech");
		prop.setProperty("Google", "http://google.com");
		prop.setProperty("Yahoo", "http://yahoo.com");
		// store the file into local system
		prop.store(fis, null);
	}
}


output-properties-file-java-selenium

Dropdown Operations in selenium webdriver

Compare Screenshots in selenium

Read All Values in properties file

When we are reading a property file we can look into the .properties n-number of times but sometimes we may need to read the all the properties to verify something either on application or on the properties file.

config file read-all-properties-java-selenium-webdriver

This program shows how to Read All Values in properties file


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

public class ReadAllProperties{
	public static void main(String[] args) throws Exception{
		// create file input stream object, to make file as readable by machine
		FileInputStream fis = new FileInputStream("C:\\path\\config-read-all.properties");
		// create properties class object to access all non-static methods
		Properties properties = new Properties();
		// load the required .properties file
		properties.load(fis);
		// close the file as Properties class object have all the details
		fis.close();
		// Properties work like HashTable, so we have to handle like hash table only
		Enumeration enumKeys = properties.keys();
		// iterate till the enumKeys has keys
		while (enumKeys.hasMoreElements()) {
			// move from null to first element(key), by default it will not point to first element
			String key = (String) enumKeys.nextElement();
			// fetch the property for the key
			String value = properties.getProperty(key);
			System.out.println(key + " = " + value);
		}
	}
}


output-read-all-properties-java-selenium-webdriver

Read Multiple Properties Files in Selenium Webdriver

This methods not only for selenium but also you can use where ever you use java to read properties files.

There could be a scenarios where you have read values from properties file but you might have stored them in different files.

For example : login.properties, config.txt and so on, please Read Properties file in other formats if you need more information why we are using '.txt' file

Files read-multiple-properties-files-in-selenium-webdriver

1. Everything is similar to reading a single property file
2. Only difference is when you load your property file, we have load all the property files.


prop.load(fis);
prop.load(fis2);
                        	


Complete program to read Multiple properties files

// PLEASE DO WRITE IMPORT STATEMENTS
public class ReadMultiplePropertiesFiles {
	public static void main(String[] args) throws IOException {
		// create file input stream object for the properties file
		FileInputStream fis = new FileInputStream("C:\\path\\login.properties");
		FileInputStream fis2 = new FileInputStream("C:\\path\\config.txt");
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		prop.load(fis);
		//load all the files
		prop.load(fis2);
		// get the property of "url" using getProperty()
		System.out.println(prop.getProperty("url"));
		System.out.println(prop.get("suite"));
	}
}
                        	

output-read-multiple-properties-files-in-selenium-webdriver

Up-Casting in Java and Selenium

Convert properties file values to Java Map

When we are reading a property file we can look into the .properties n-number of time but it takes lot of memory and process to read the value each time from the file.

To avoid this in our frameworks we have to keep all the properties in a map, so that we can retrieve the values from this map when it is required

This program shows how to Convert properties file values to Java Map


import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesToJavaMap {
	public static void main(String[] args) throws Exception {
		// declare a map which store string as key and string as value
		Map mapProp = new HashMap();
		// create file input stream object, to make file as readable by machine
		FileInputStream fis = new FileInputStream("C:\\path\\read-all.properties");
		// create properties class object to access all non-static methods
		Properties prop = new Properties();
		// load the required .properties file
		prop.load(fis);
		// close the file as Properties class object have all the details
		fis.close();
		// Properties work like HashTable, so we have to handle like hash table only
		Enumeration enumKeys = prop.keys();
		// iterate till the enumKeys has keys
		while (enumKeys.hasMoreElements()) {
			// move from null to first element(key), by default it will not point to first element
			String key = (String) enumKeys.nextElement();
			// fetch the property for the key
			String value = prop.getProperty(key);
			// store the key and value in map
			mapProp.put(key, value);
		}
		System.out.println("Value stored to Map are : "+mapProp);
	}
}

Output :
output-properties-file-java-map

Convert Java Map to properties file

Sometimes we may in a situation where we have to store the java map to properties file, end of the we have to store the value for retrieving in future.

config file read-all-properties-java-selenium-webdriver

This program shows how to Convert Java Map to properties file


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class JavaMapToProperties {
	public static void main(String[] args) throws IOException {
		// declare a map which store string as key and string as value
		Map mapProp = new HashMap();
		
		mapProp.put("Name", "unknow");
		mapProp.put("Age", "27");
		mapProp.put("Gende", "Male");
		
		File file = new File("C:\\path\\map-to-file.properties");
		// create file input stream object for the properties file
		FileOutputStream fos = new FileOutputStream(file);
		// create Properties class object to access properties file
		Properties prop = new Properties();
		// load the properties file
		
		Iterator keys = mapProp.keySet().iterator();
		
		while (keys.hasNext()) {
			String key = keys.next();
			prop.setProperty(key, mapProp.get(key));
		}
		prop.store(fos, null);
	}
}
						

Output :
java-map-to-properties-file

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech