Read simple YAML file with JAVA
We know YAML file is used as configuration file, to store and transmit data. So YAML file can be used to store test data in Test Automation. The test data can be:
- User id and password
- Search Keyword etc
Lets see what all we need to read a YAML file using Java.
- yaml file
- libraries (in this blog Jackson library is used)
- IDE (Eclipse : Neon 3 (release 4.6.3))
yaml file
empName: Test User age: 30 empTitle: Software Engineer
Libraries
For this blog Jackson libraries is used to parse the yaml file. Its quite popular library and used by many. We will add the maven dependencies in the pom.xml file.
<dependencies> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> </dependencies>
Map the yaml file to the instance of the class
Create a class : Emp to hold our yaml file data
package readyamlfile.readyamlfile; public class Emp { private String empName; private int age; private String empTitle; public Emp(String empName, int age, String empTitle){ this.empName=empName; this.age = age; this.empTitle = empTitle; } //The following constructor is required. You remove and see what happens public Emp(){ } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmpTitle() { return empTitle; } public void setEmpTitle(String empTitle) { this.empTitle = empTitle; } }
Jackson’s YamlFactory to read yaml file to Emp bean
package readyamlfile.readyamlfile; import java.io.File; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; public class ReadEmp { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); //ObjectMapper is used to map the yaml content to basic POJOs try { File file = new File("C:\\yml\\emp.yml"); //I have stored the yml file in my local c drive Emp emp = mapper.readValue(file, Emp.class); System.out.println(emp.getEmpName()); } catch (Exception e) { } } }
Run the above class
Once the above class is run, following should be printed to console:
Test User
You can also refer to Jackson library github for more details. Link: https://github.com/FasterXML/jackson-dataformats-text/tree/master/yaml