Read a CSV File

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to read a CSV file using Java programming language. CSV (Comma Separated Values) is a file format used to store and exchange data between systems. We will use two methods to read the CSV file: using the OpenCSV library and using the Scanner class.

Import Libraries

We will need to import library dependencies to use OpenCSV and Scanner classes in our code. In the CSVReader.java file, add the following code at the beginning of the file:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import com.opencsv.CSVReader;

Read CSV file using OpenCSV Library

We can use the OpenCSV library to read the CSV file. The following code snippet shows how to read a CSV file using OpenCSV.

try {
    FileReader fileReader = new FileReader("students.csv");
    CSVReader csvReader = new CSVReader(fileReader);
    String[] nextRecord;
    while ((nextRecord = csvReader.readNext()) != null) {
        System.out.println(nextRecord[0] + " " + nextRecord[1] + " " + nextRecord[2]);
    }
    csvReader.close();
} catch (IOException e) {
    System.out.println(e.getMessage());
}

Save the changes and run the following command in the terminal to compile and run the code:

javac CSVReader.java && java CSVReader

This code will read the CSV file named students.csv in the current directory and print the CSV data to the console.

Read CSV file using Scanner class

We can also use the Scanner class to read the CSV file. The following code snippet shows how to do it:

try {
    File file = new File("students.csv");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(",");
    while (scanner.hasNext()) {
        System.out.print(scanner.next() + " ");
    }
    scanner.close();
} catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
}

In this example, we are using the Scanner class to read a file named students.csv and specifying a delimiter , to separate the CSV values.

Save the changes and run the following command in the terminal to compile and run the code:

javac CSVReader.java && java CSVReader

This code will read the CSV file named students.csv in the current directory and print the CSV data to the console.

Summary

In this lab, we learned how to read a CSV file using Java programming language. We used two methods to read the CSV file: using OpenCSV library and using Scanner class. The OpenCSV library provides a convenient way to read the CSV file but requires an external dependency. The Scanner class provides a simple way to read the CSV file but has some limitations in handling complex CSV structures.

Other Java Tutorials you may like