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.

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