Reading a CSV File

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to read a CSV file in Java. CSV files are often used to store data in a simple and easily readable format. We will cover three different approaches to reading CSV files in Java: using BufferedReader, Scanner, and the OpenCSV library.


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/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") 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/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117982{{"`Reading a CSV File`"}} java/scope -.-> lab-117982{{"`Reading a CSV File`"}} java/generics -.-> lab-117982{{"`Reading a CSV File`"}} java/arraylist -.-> lab-117982{{"`Reading a CSV File`"}} java/classes_objects -.-> lab-117982{{"`Reading a CSV File`"}} java/class_methods -.-> lab-117982{{"`Reading a CSV File`"}} java/exceptions -.-> lab-117982{{"`Reading a CSV File`"}} java/modifiers -.-> lab-117982{{"`Reading a CSV File`"}} java/oop -.-> lab-117982{{"`Reading a CSV File`"}} java/packages_api -.-> lab-117982{{"`Reading a CSV File`"}} java/user_input -.-> lab-117982{{"`Reading a CSV File`"}} java/files -.-> lab-117982{{"`Reading a CSV File`"}} java/read_files -.-> lab-117982{{"`Reading a CSV File`"}} java/identifier -.-> lab-117982{{"`Reading a CSV File`"}} java/arrays -.-> lab-117982{{"`Reading a CSV File`"}} java/comments -.-> lab-117982{{"`Reading a CSV File`"}} java/data_types -.-> lab-117982{{"`Reading a CSV File`"}} java/for_loop -.-> lab-117982{{"`Reading a CSV File`"}} java/operators -.-> lab-117982{{"`Reading a CSV File`"}} java/output -.-> lab-117982{{"`Reading a CSV File`"}} java/strings -.-> lab-117982{{"`Reading a CSV File`"}} java/variables -.-> lab-117982{{"`Reading a CSV File`"}} java/while_loop -.-> lab-117982{{"`Reading a CSV File`"}} java/string_methods -.-> lab-117982{{"`Reading a CSV File`"}} java/system_methods -.-> lab-117982{{"`Reading a CSV File`"}} end

Set up the project

We will create a new Java project in the ~/project directory. Let's create a new Java class named CSVReaderDemo.java in the src directory by running the following command in the terminal:

cd ~/project
mkdir src
javac -d src src/CSVReaderDemo.java

Open CSVReaderDemo.java in a text editor.

Reading CSV files using BufferedReader

We will use BufferedReader class of java.io package to read the CSV file. The following code demonstrates how to read a CSV file using BufferedReader:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class CSVReaderDemo {
    public static void main(String[] args) {
        try {
            List<List<String>> data = new ArrayList<>(); // list of lists to store data
            String file = "path/to/csv/file.csv"; // replace with the path to your own CSV file
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            // Reading until we run out of lines
            String line = br.readLine();
            while (line != null) {
                List<String> lineData = Arrays.asList(line.split(","));
                data.add(lineData);
                line = br.readLine();
            }

            // Printing the fetched data
            for (List<String> list : data) {
                for (String str : list) {
                    System.out.print(str + " ");
                }
                System.out.println();
            }

            br.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

To run the code, execute the following command in the terminal:

cd ~/project
java -cp src CSVReaderDemo

Reading CSV files using Scanner

We can also use the Scanner class of java.util package to read a CSV file. The following code demonstrates how to read a CSV file using Scanner:

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Arrays;

public class CSVReaderDemo {
    public static void main(String[] args) {
        try {
            List<List<String>> data = new ArrayList<>();
            String filePath = "path/to/csv/file.csv"; // replace with the path to your own CSV file
            File file = new File(filePath);
            Scanner s = new Scanner(file);

            while (s.hasNextLine()) {
                List<String> lineData = Arrays.asList(s.nextLine().split(","));
                data.add(lineData);
            }

            for (List<String> list : data) {
                for (String str : list) {
                    System.out.print(str + " ");
                }
                System.out.println();
            }

            s.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
To run the code, execute the following command in the terminal:

cd ~/project
java -cp src CSVReaderDemo

Reading CSV files using OpenCSV library

We can use the OpenCSV library for more complex CSV files. We will create a CSVReader object and use the readNext() method to read lines of the CSV file. The following code demonstrates how to read a CSV file using OpenCSV:

import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVReader;
import java.util.Arrays;

public class CSVReaderDemo {
    public static void main(String[] args) {
        try {
            List<List<String>> data = new ArrayList<>();
            String filePath = "path/to/csv/file.csv"; // replace with the path to your own CSV file
            FileReader fr = new FileReader(filePath);
            CSVReader reader = new CSVReader(fr);

            String[] lineData = reader.readNext();
            while (lineData != null) {
                data.add(Arrays.asList(lineData));
                lineData = reader.readNext();
            }

            for (List<String> list : data) {
                for (String str : list) {
                    System.out.print(str + " ");
                }
                System.out.println();
            }

            reader.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

To run the code, execute the following command in the terminal:

cd ~/project
java -cp ".:lib/*:src" CSVReaderDemo

Summary

In this lab, we learned three different approaches to reading CSV files in Java: using BufferedReader, Scanner, and the OpenCSV library. BufferedReader and Scanner are both good options for simple CSV files, while OpenCSV is better for more complex CSV files. Now you should be able to read CSV files in Java with ease!

Other Java Tutorials you may like