0
0
Selenium Javatesting~5 mins

CSV data reading in Selenium Java

Choose your learning style9 modes available
Introduction

Reading CSV data helps tests use many inputs easily. It saves time by reusing data from files.

You want to test a login page with many usernames and passwords.
You need to check a form with different sets of input values.
You want to run the same test multiple times with different data.
You have test data maintained by others in a CSV file.
You want to separate test data from test code for clarity.
Syntax
Selenium Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CsvReader {
    public static void readCsv(String filePath) {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                // Use values here
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Use BufferedReader and FileReader to read CSV files line by line.

Split each line by comma , to get individual values.

Examples
This splits a CSV line into parts and prints the first value.
Selenium Java
String line = "John,Doe,30";
String[] values = line.split(",");
System.out.println(values[0]); // John
This reads a CSV file and prints the second value of each line.
Selenium Java
try (BufferedReader br = new BufferedReader(new FileReader("data.csv"))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(",");
        System.out.println(values[1]);
    }
}
Sample Program

This program reads a CSV file named testdata.csv with username and password pairs. It prints each pair.

Selenium Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CsvDataTest {
    public static void main(String[] args) {
        String filePath = "testdata.csv";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split(",");
                System.out.println("Username: " + data[0] + ", Password: " + data[1]);
            }
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}
OutputSuccess
Important Notes

CSV files should not have extra commas inside values unless handled carefully.

Always close file readers or use try-with-resources to avoid resource leaks.

For complex CSV files, consider using libraries like OpenCSV.

Summary

CSV reading helps run tests with many data sets easily.

Use BufferedReader and split lines by commas to get data.

Keep test data separate from code for better maintenance.