Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of reading CSV file with current apache commons csv library

Tags:

java

csv

apache

Can someone please provide me with an example of reading a CSV file with the Apache commons CSVParser class? I see countless examples that use the outdated (I think) API that has been impossible to find.

Everywhere I look, I see this:

File csvData = new File("/path/to/csv");
CSVParser parser = CSVParser.parse(csvData, CSVFormat.RFC4180);
for (CSVRecord csvRecord : parser) {
    ...
}

But nowhere can I find a jar file that has a CSVParser.parse() method that takes those parameters. The one that takes a File object, also takes a Charset parameter after it. All over the place I see the API describe that literally doesn't seem to exist. I'm guessing it was a pre-1.0 API that they removed once 1.0 was released. I've tried 1.0, 1.1. and 1.2 in my pom file dependency, but they all have the method with the Charset parameter.

like image 385
Brent212 Avatar asked Apr 21 '16 00:04

Brent212


People also ask

How does Apache Commons read CSV files?

csv . It's very easy to read such CSV files with Apache Commons CSV. You just need to add a single setting called withFirstRecordAsHeader() . Apache Commons CSV uses the first record as the header record and allows you to retrieve the values using the header names.

What is Apache Commons CSV?

Using Apache Commons CSV Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format. The most common CSV formats are predefined in the CSVFormat class: Microsoft Excel.

Can we read csv file with Apache POI?

Apache POI was never designed to call on CSV files. While a CSV File may be opened in Excel, Excel has its own reader that does an auto import. This is assuming that your CSV has the . csv instead of the .

How do I view a CSV file?

Opening a CSV file is simpler than you may think. In almost any text editor or spreadsheet program, just choose File > Open and select the CSV file. For most people, it is best to use a spreadsheet program. Spreadsheet programs display the data in a way that is easier to read and work with than a text editor.


1 Answers

I ended up just doing this:

CSVParser csvFileParser = CSVFormat.DEFAULT.parse(new FileReader(new File("/path/to/csv")));

Still blows my mind that all articles and official apache documentation show examples using a method that doesn't appear to exist.

like image 160
Brent212 Avatar answered Oct 01 '22 12:10

Brent212