Reading a CSV File in Java

Profile picture for user arilio666

This article will show how to read a CSV file using the opencsv library.

  • Incorporate the OpenCSV library into your project. You can add the library to your project by downloading it from the OpenCSV website or using maven
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.1</version>
</dependency>
  • Make a CSVReader object and send the CSV file as an argument.
  • To read the following line of the CSV file as an array of Strings, use the CSVReader object's readNext() function.
  • Using a loop, go over the lines of the CSV file and treat each line as needed.

Here's our CSV file content.

Reading a CSV File in Java

Example:

package week1.day2;
import java.io.FileReader;
import java.io.IOException;
import com.opencsv.CSVReader;
public class Calculator {
    public static void main(String[] args) throws Exception {
        String csvFile = "C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\Book1.csv";
        try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
            String[] line;
            while ((line = reader.readNext()) != null) {
                // Process the line as needed
                for (String element : line) {
                    System.out.print(element + ", ");
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • We create a CSVReader object by passing a FileReader object that reads the CSV file. 
  • We then use the readNext() method to read each line of the CSV file as an array of Strings. 
  • Finally, we process each line by iterating over the array and printing each element to the console.
  • Reading a CSV File in Java
Tags