In eclipse create a file with the name config.properties
browser = mozila
url = qa.companyname.com
dbusername = root
dbpassword = root
uploadDir = //upload//screenshots
screenshotsAlways = Y
screenshotsOnlyOnFailure = Y
implicitwait = 30
Property file is used for configuration purpose.
This is not for test data, but for configuration data.
This file is loaded at start while configuring any application
All methods of this class are synchronized. So it is thread safe class.
It has been since from jdk 1.0.
It is the subclass of HashTable.
It stores the key-value pair, but both as a string.
It can used to get property value based on property key.
It can be used to get properties of the system.
It provides easy maintenance.
It can be used to get properties from an xml file or to store data in xml file.
package com.javabykiran.collection;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/*
* @author Java By Kiran
*/
public class PropertiesTest {
public static void main(String[] args) {
Properties properties = new Properties();
// Same way we can put elements properties.put(“101”, “java”);
properties.put(“102”, “C”);
properties.put(“103”, “C++”);
properties.put(“104”, “.Net”);
// to retrieve the elements.
Set s = properties.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
System.out.println(properties.get((String) itr.next()));
}
// to store in xml file
try {
FileOutputStream fout = new FileOutputStream (“D:\\prop.xml”);
properties.storeToXML (fout, “key-value pair”);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Net
C++
C
Java
Also XML file is created as below in D drive.
<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE properties SYSTEM “http://java.sun.com/dtd/
properties.dtd”>
<properties>
<comment>key-value pair</comment>
<entry key=”104”>.Net</entry>
<entry key=”103”>C++</entry>
<entry key=”102”>C</entry>
<entry key=”101”>java</entry>
</properties>
Step 1: Create a properties file in ‘D drive’ as shown below and save with the name login. properties [make changes in the program according to the location of the path you choose]
username=Kiran
password=kiran
url=qa.xyz.com
Step 2: Write below given program to read a file. In this program, we read one of the property names i.e. ‘username’.
package com.jbk;
import java.io.FileInputStream;
import java.util.Properties;
public class ReadPropertyFile {
public static void main(String[] args) throws Exception {
FileInputStream inStream = new FileInputStream(“D:\\login.properies”);
Properties properties = new Properties();
properties.load(inStream);
System.out.println(properties.getProperty(“username”));
}
}
Step 3: Run the program and see the output.
Note: If you look at the above program in Java program, no values are used so that in the near future even if username needs to be changed, it can be changed in the properties file itself which can also be done by a non-technical person.