How to read csv file in java?

To read a CSV file in Java, you can use the OpenCSV library, which is a very simple and easy to use library that allows you to work with CSV files in Java.

Here’s a basic example of how you can read a CSV file:

  1. First, you have to add the OpenCSV library to your Java project.
    You can download it from here, http://opencsv.sourceforge.net/, or if you’re using a build system like Maven, you can add it to your pom.xml:
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.2</version>
</dependency>
  1. Here’s a basic example of how to read records from a CSV file:
import com.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;

public class CSVReaderExample {
    public static void main(String[] args) {
        String csvFile = "/path/to/your/csvfile.csv";
        CSVReader reader = null;
        try {
            reader = new CSVReader(new FileReader(csvFile));
            String[] line;
            while ((line = reader.readNext()) != null) {
                System.out.println("Column 1: " + line[0] + " Column 2: " + line[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

This will read the CSV file line by line and print out the first two columns of each line.

Remember to replace “/path/to/your/csvfile.csv” with the path to the actual CSV file that you want to read.

Leave a Reply

Your email address will not be published. Required fields are marked *