How to parse CSV files in Java

CSV is widely used format and quite often used across projects. Let’s see how to parse CSV files in Java

Assumptions
You have a maven project setup. If not quickly browse through How to create a simple Java project in Maven

We would be reusing the file reading snippet from earlier post How to read Text Files in Java

We shall use opencsv library for parsing.

Setting Maven

Using CSV Parser

If we re-use our Java program, we can implement the processLine() API to parse the CSV lines. Let’s see the code

Here we use the CSV parser. We initialise the CSV parser passing it the separator char. You can specify tab char or any other char as well. Once we get the line, we just need to call the parser and get the array of columns back. Here we just print them, you can process them in application specific manner.

It’s important to see how we are building small utility functions and reusing them across posts. It helps to have them handy in real life as well.

Using CSV Reader

We can use CSVReader to read our file as well. It’s very similar to our text file reading code, instead of String, here we get String[]. Let’s see the code

Here the file reading part has been wrapped under the API. The API has lot of variations to handle lot of real world use cases, best is to explore.

Leave a Reply

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