CSV is one of the fastest way to read and write data during test automation.
Benefits of CSV over Excel:
CSV is better than Excel in many cases, specially when it comes to test data or any data that we store to use within test framework.
Below are few reasons where CSV is better than Excel:
- CSV is lightweight and faster than excel with respect to read / write operation
- CSV takes up less space than Excel
- CSV is compatible with versioning systems like Git as Excel is not suitable for Git to track changes
- CSV can be used by the test automation script while it is open , Excel sheet needs to be closed before running test script.
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.2</version>
</dependency>
Read CSV file and return 2D Object array:
public static Object[][] readCsv(File file) throws JsonProcessingException {
Object obj[][]=null;
try {
// Create an object of filereader
// class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
//Skipping Header
CSVReader csvReader =
new CSVReaderBuilder(filereader).withSkipLines(1).build();
List<String[]> allData = csvReader.readAll();
int rowCount = allData.size();
System.out.println("Row count= " + rowCount);
String[] headers = allData.get(0);
int colCount = headers.length;
System.out.println("Col count=" + colCount);
obj = new Object[rowCount][colCount];
for (int i = 0, j = 0; i < rowCount; i++) {
while (j < colCount) {
String[] rowData = allData.get(i);
for (String cell : rowData) {
System.out.print("Row: " + i + "Cell= " + j);
obj[i][j] = cell;
System.out.println(" | " + obj[i][j]);
j++;
}
}
j = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
//To print 2D array
System.out.println("CSV Data : "+Arrays.deepToString(obj));
return obj;
}
Know More about CSV operation: https://www.geeksforgeeks.org/reading-csv-file-java-using-opencsv/