Read CSV File in Java

Reading a CSV (Comma Separated Values) file in Java is a common task, especially when dealing with data exchange between different applications. Java provides several ways to read a CSV file, including using the built-in `BufferedReader` class, the `Scanner` class, or third-party libraries like OpenCSV.

Using BufferedReader

How To Read Csv Files Using Java

One of the simplest ways to read a CSV file in Java is by using the BufferedReader class. This class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadCSV {
    public static void main(String[] args) {
        String csvFile = "path/to/your/file.csv";
        String line = "";
        String cvsSplitBy = ",";

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            while ((line = br.readLine())!= null) {
                // use comma as separator
                String[] country = line.split(cvsSplitBy);
                System.out.println("Country [code=" + country[4] + ", name=" + country[5] + "]");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Scanner

The Scanner class can also be used to read a CSV file. It breaks the input into tokens based on a delimiter, which can be a comma for CSV files.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadCSV {
    public static void main(String[] args) {
        String csvFile = "path/to/your/file.csv";
        try {
            File file = new File(csvFile);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] values = line.split(",");
                System.out.println("Value 1: " + values[0] + ", Value 2: " + values[1]);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Using OpenCSV

How To Load Data From Csv File In Java Example Java67

OpenCSV is a popular third-party library for reading and writing CSV files in Java. It provides more flexibility and control over the parsing process compared to using BufferedReader or Scanner alone.

import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

import java.io.FileReader;
import java.io.IOException;

public class ReadCSV {
    public static void main(String[] args) {
        String csvFile = "path/to/your/file.csv";
        try {
            CSVReader csvReader = new CSVReaderBuilder(new FileReader(csvFile))
                   .withSkipLines(1) // skip header
                   .build();
            String[] nextLine;
            while ((nextLine = csvReader.readNext())!= null) {
                System.out.println("Name : " + nextLine[0] + ", Age : " + nextLine[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
MethodDescription
BufferedReaderSimple, built-in Java class for reading text files line by line.
ScannerAlso built-in, it breaks input into tokens based on a delimiter, useful for CSV.
OpenCSVThird-party library offering more features and control over CSV parsing.
Java Buddy Java To Read Csv File
💡 Choosing the right method to read a CSV file in Java depends on the complexity of the task, the size of the file, and the specific requirements of the project. For simple tasks, `BufferedReader` or `Scanner` might suffice, but for more complex scenarios, leveraging the capabilities of OpenCSV can be beneficial.

Key Points

  • Use `BufferedReader` for simple CSV reading tasks, leveraging its line-by-line reading capability.
  • Consider `Scanner` for its token-based approach, which can be handy for CSV files.
  • For advanced CSV parsing needs, OpenCSV provides a robust solution with numerous features.
  • When choosing a method, consider the size of the CSV file and the specific parsing requirements.
  • Always handle potential exceptions, such as `IOException` or `FileNotFoundException`, to ensure robustness.

What is the most efficient way to read a large CSV file in Java?

+

For large CSV files, using BufferedReader with a decent buffer size or employing a library like OpenCSV that is optimized for performance can be efficient. However, the best approach depends on the file’s size, the available memory, and the processing requirements.

How do I handle quoted values in a CSV file that contain commas?

+

When using BufferedReader or Scanner, handling quoted values that contain commas can be challenging. OpenCSV provides built-in support for quoted values, making it a preferred choice for such scenarios.

Can I use Java 8 Stream API to read a CSV file?

+

Yes, Java 8’s Stream API can be used in conjunction with Files.lines() or Files.readAllLines() to read a CSV file, offering a more functional programming approach to parsing CSV files.