# How to read and parse a CSV file in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 11, 2020, updated Sep 24, 2022. Topics: Java, CSV.
Canonical URL: https://attacomsian.com/blog/java-read-parse-csv-file

> A detailed guide to learning how to read and parse a CSV file using core Java, OpenCSV, and Apache Commons CSV.

A Comma Separated Values (CSV) file is a simple text file that stores data in a tabular format, where columns are separated by a delimiter (usually a comma or a tab). These files are typically used for importing and exporting data between servers and applications.

In my previous articles, I wrote about reading and write CSV files using [core Java](https://attacomsian.com/blog/read-write-csv-files-core-java), [OpenCSV](https://attacomsian.com/blog/read-write-csv-files-opencsv), [Apache Common CSV](https://attacomsian.com/blog/read-write-csv-files-apache-commons-csv), and [Spring Boot](https://attacomsian.com/blog/export-download-data-csv-file-spring-boot). 

In this article, we shall look at different ways to read and parse a CSV file in Java.

Here is an example of a simple CSV file that uses a comma (`,`) as a delimiter to separate column values and doesn't contain any double-quote:

<p class="file-desc"><span>users.csv</span></p>

```csv
1,John Doe,john@example.com,AE
2,Alex Jones,alex@example.com,DE
3,Jovan Lee,jovan@example.com,FR
4,Greg Hover,greg@example.com,US
```

## Read CSV File using Core Java

To read and parse a simple CSV like the above that *doesn't* contain the delimiter inside column values, core Java classes can be used. You can either use the [BufferedReader](https://attacomsian.com/blog/java-read-file-using-bufferedreader) class or the `Scanner` class to easily [read the file](https://attacomsian.com/blog/java-read-write-files) in Java.

### `BufferedReader` Class

Since CSV is just a plain-text file, the `BufferedReader` class can be used to [read it line by line](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java). You can then use the `String.split()` method to [split each line by comma](https://attacomsian.com/blog/java-string-split) to convert it into columns. Here is an example:

```java
// create a reader
try (BufferedReader br = Files.newBufferedReader(Paths.get("users.csv"))) {

    // CSV file delimiter
    String DELIMITER = ",";

    // read the file line by line
    String line;
    while ((line = br.readLine()) != null) {

        // convert line into columns
        String[] columns = line.split(DELIMITER);

        // print all columns
        System.out.println("User["+ String.join(", ", columns) +"]");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}
```

Here is what the output looks like:

```bash
User[1, John Doe, john@example.com, AE]
User[2, Alex Jones, alex@example.com, DE]
User[3, Jovan Lee, jovan@example.com, FR]
User[4, Greg Hover, greg@example.com, US]
```

### `Scanner` Class

Another way of reading and parsing a CSV file in core Java is using the `Scanner` class. This class converts its input into tokens using a delimiter pattern. The resulting tokens may then be converted into values of different types using different `next()` methods.

Here is an example that shows how you can use `Scanner` to read and parse a CSV file:

```java
// create scanner instance
try (Scanner scanner = new Scanner(Paths.get("users.csv").toFile())) {

    // CSV file delimiter
    String DELIMITER = ",";

    // set comma as delimiter
    scanner.useDelimiter(DELIMITER);

    // read all fields
    while (scanner.hasNext()) {
        System.out.print(scanner.next() + " ");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}
```

The above code will output the following on the console:

```java
1 John Doe john@example.com AE
2 Alex Jones alex@example.com DE
3 Jovan Lee jovan@example.com FR
4 Greg Hover greg@example.com US
```

> Check out the [Reading and Writing CSV files using core Java](https://attacomsian.com/blog/read-write-csv-files-core-java) tutorial for more examples.

## Read CSV File using OpenCSV

[OpenCSV](https://attacomsian.com/blog/read-write-csv-files-opencsv) is a popular library for reading, writing, parsing, serializing, and deserializing CSV files in Java. This library is a good choice for handling different CSV formats, delimiters, and special characters.

To add OpenCSV support to your Gradle project, add the following dependency to the `build.gradle` file:

```groovy
implementation 'com.opencsv:opencsv:5.0'
```

For Maven, add the below dependency to your `pom.xml` file:

```xml
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.0</version>
</dependency>
```

The following example demonstrates how you can read and parse a CSV file named `users.csv` using OpenCSV:

```java
// create a csv reader
try (Reader reader = Files.newBufferedReader(Paths.get("users.csv"));
     CSVReader csvReader = new CSVReader(reader)) {

    // read one record at a time
    String[] record;
    while ((record = csvReader.readNext()) != null) {
        System.out.println("User["+ String.join(", ", record) +"]");
    }

} catch (IOException | CsvValidationException ex) {
    ex.printStackTrace();
}
```

The above example will output the following on the console:

```bash
User[1, John Doe, john@example.com, AE]
User[2, Alex Jones, alex@example.com, DE]
User[3, Jovan Lee, jovan@example.com, FR]
User[4, Greg Hover, greg@example.com, US]
```

> Check out [OpenCSV tutorial](https://attacomsian.com/blog/read-write-csv-files-opencsv) to dig deeper and learn more about OpenCSV. 


## Read CSV File using Apache Commons CSV

[Apache Commons CSV](https://commons.apache.org/proper/commons-csv/) is another 3rd-party library for reading and parsing CSV files in Java. It provides several ways to read CSV files in different formats.

For a Gradle project, add the following dependency to the `build.gradle` file to import Commons CSV:

```groovy
implementation 'org.apache.commons:commons-csv:1.7'
```

For Maven, add the below dependency to your `pom.xml` file:

```xml
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.7</version>
</dependency>
```

Here is an example that shows how you can use the Apache Commons CSV library to read and parse the contents of a CSV file in Java:

```java
// create a reader
try (Reader reader = Files.newBufferedReader(Paths.get("users.csv"))) {

    // read csv file
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);
    for (CSVRecord record : records) {
        System.out.println("Record #: " + record.getRecordNumber());
        System.out.println("ID: " + record.get(0));
        System.out.println("Name: " + record.get(1));
        System.out.println("Email: " + record.get(2));
        System.out.println("Country: " + record.get(3));
    }

} catch (IOException ex) {
    ex.printStackTrace();
}
```

The above example will print the following on the console:

```java
Record #: 1
ID: 1
Name: John Doe
Email: john@example.com
Country: AE
Record #: 2
ID: 2
Name: Alex Jones
Email: alex@example.com
Country: DE
Record #: 3
ID: 3
Name: Jovan Lee
Email: jovan@example.com
Country: FR
Record #: 4
ID: 4
Name: Greg Hover
Email: greg@example.com
Country: US
```

> Check out [Apache Commons CSV tutorial](https://attacomsian.com/blog/read-write-csv-files-apache-commons-csv) for a deeper understanding of how It works and how you can use it to read and write different CSV formats.

## Conclusion

That's all for reading and parsing a CSV file in Java. We talked about different ways of reading and parsing a CSV file, including core Java and 3rd-party libraries like OpenCSV and Apache Commons CSV. 

For simple CSV file formats where column values do not contain the delimiter itself, core Java is a good choice. 

For more complex CSV file formats, you should rely on a 3rd-party library like OpenCSV or Apache Commons CSV for correctly parsing the data. Personally, I prefer to use OpenCSV because it supports multiple CSV formats, special characters, and more.

If you want to create and download a CSV file in a Spring Boot application, check out [this excellent tutorial](https://attacomsian.com/blog/export-download-data-csv-file-spring-boot) I wrote a while ago.
