All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

How To Read A CSV File In Java

Last Updated : Mar 11, 2024

How To Read A CSV File In Java

In this article we will show you the solution of how to read a csv file in java, working with data frequently involves reading a CSV (Comma-Separated Values) file in Java. Use Java's CSV parsing libraries, such as Apache Commons CSV or OpenCSV, to carry out this task.

Here is a quick overview of reading CSV files in Java.

The required library must first be included in your project.

You can accomplish this by either downloading the library and manually importing it or by adding the necessary dependency to your project's build file.

You can begin reading the CSV file after setting up the library. To open the file, create a FileReader object, and then send it to the library's CSV parser.

Utilize the library's API to iterate through the CSV file's rows and get the data in each row.

By indicating either the column index or header name, you can retrieve values from any given column. We'll talk about how to read a CSV file in Java now.

Step By Step Guide On How To Read A CSV File In Java :-

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class CSVReaderExample {
    public static void main(String[] args) {
        String csvFilePath = "path/to/your/csv/file.csv";
        try (Reader reader = new FileReader(csvFilePath);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {
            for (CSVRecord csvRecord : csvParser) {
                // Accessing values by column index
                String column1 = csvRecord.get(0);
                String column2 = csvRecord.get(1);
                // ...
                // Accessing values by header name
                String header1 = csvRecord.get("Header1");
                String header2 = csvRecord.get("Header2");
                // ...
                // Process the data
                System.out.println("Column 1: " + column1);
                System.out.println("Column 2: " + column2);
                // ...
                System.out.println("Header 1: " + header1);
                System.out.println("Header 2: " + header2);
                // ...
        } catch (IOException e) {
  1. In order to import the essential classes from the Apache Commons CSV library, we utilise the import statements at the beginning of the code. For managing and parsing CSV files, these classes are utilised.
  2. The main function, which has the CSV reading logic, is where we declare the CSVReaderExample class.
  3. The path to the CSV file we wish to read is initialised in the main method's String variable csvFilePath, which is declared. The real file path should be substituted for "path/to/your/csv/file.csv".
  4. After that, the actual CSV reading and parsing is done in a try block. A catch clause is placed after the try block to deal with any IOExceptions that may arise when reading or parsing files.
  5. We establish a FileReader object in the try block by providing the constructor with the csvFilePath. The CSV file must be read by this FileReader.
  6. The reader, which is the FileReader object, and CSVFormat.DEFAULT are then sent to the constructor of the CSVParser object, which is then created. CSVFormat.The default format for parsing the CSV file is specified by DEFAULT.
  7. Then, to traverse through each CSVRecord in the csvParser, we enter a for loop. A row in the CSV file is represented by each CSVRecord.
  8. Either the column index or the header name can be used within the loop to get the values in each row. While csvRecord.get("Header1") and csvRecord.get("Header2") access values by header name in the code example, csvRecord.get(0) and csvRecord.get(1) access values by column index. The header names from your CSV file should be used in place of "Header1", "Header2", etc.
  9. You can process the data as necessary after you have access to the values. The values are output to the console in the code example using System.out.println(). You can carry out any actions you like or save the data in the right data structures.
  10. The catch section then deals with any IOExceptions that may arise when reading or parsing files. When an exception occurs, e.printStackTrace() prints the stack trace to the console.

Conclusion :-

As a result, we have successfully acquired the knowledge necessary to read a CSV file in Java.

We also discovered that using a CSV parsing library like Apache Commons CSV is necessary in order to read a CSV file in Java.

I hope this article on how to read a csv file in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪