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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/FileandIOManagementGroup -.-> java/read_files("`Read Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117442{{"`Read a CSV File`"}} java/exceptions -.-> lab-117442{{"`Read a CSV File`"}} java/oop -.-> lab-117442{{"`Read a CSV File`"}} java/packages_api -.-> lab-117442{{"`Read a CSV File`"}} java/user_input -.-> lab-117442{{"`Read a CSV File`"}} java/files -.-> lab-117442{{"`Read a CSV File`"}} java/read_files -.-> lab-117442{{"`Read a CSV File`"}} java/identifier -.-> lab-117442{{"`Read a CSV File`"}} java/arrays -.-> lab-117442{{"`Read a CSV File`"}} java/data_types -.-> lab-117442{{"`Read a CSV File`"}} java/operators -.-> lab-117442{{"`Read a CSV File`"}} java/output -.-> lab-117442{{"`Read a CSV File`"}} java/strings -.-> lab-117442{{"`Read a CSV File`"}} java/while_loop -.-> lab-117442{{"`Read a CSV File`"}} java/system_methods -.-> lab-117442{{"`Read a CSV File`"}} end

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