We need to tell the parser to process the header line for us. We specify that as part of the CSVFormat, so we'll create a custom format like this:
CSVFormat csvFormat = CSVFormat.RFC4180.withFirstRecordAsHeader();
Question code used DEFAULT, but this is based on RFC4180 instead. Comparing them side-by-side:
DEFAULT RFC4180 Comment
=================================== =========================== ========================
withDelimiter(',') withDelimiter(',') Same
withQuote('"') withQuote('"') Same
withRecordSeparator("\r\n") withRecordSeparator("\r\n") Same
withIgnoreEmptyLines(true) withIgnoreEmptyLines(false) Don't ignore blank lines
withAllowDuplicateHeaderNames(true) - Don't allow duplicates
=================================== =========================== ========================
withFirstRecordAsHeader() We need this
With that change, we can call get(String name) instead of get(int i):
User currentUser = new User(
Integer.parseInt(csvRecord.get("id")),
csvRecord.get("first"),
csvRecord.get("last"),
csvRecord.get("city")
);
Note that CSVParser implements Iterable<CSVRecord>, so we can use a for-each loop, which makes the code look like this:
String path = "./data/data.csv";
Map<Integer, User> map = new HashMap<>();
try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(Paths.get(path)),
CSVFormat.RFC4180.withFirstRecordAsHeader())) {
for (CSVRecord csvRecord : csvParser) {
User currentUser = new User(
Integer.parseInt(csvRecord.get("id")),
csvRecord.get("first"),
csvRecord.get("last"),
csvRecord.get("city")
);
map.put(currentUser.getId(), currentUser);
}
}
That code correctly parses the file, even if the column order changes, e.g. to:
last,first,id,city
doe,john,1,austin
mary,jane,2,seattle
Answer from Andreas on Stack OverflowApache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVParser.html
CSVParser (Apache Commons CSV 1.14.2-SNAPSHOT API)
Parses the CSV input according to the given format and returns the content as a list of CSVRecords. ... Gets the trailer comment, if any. ... Checks whether there is a header comment. ... Checks whether there is a trailer comment. ... Tests whether this parser is closed.
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › index.html
Overview (Apache Commons CSV 1.14.2-SNAPSHOT API)
public enum Headers { ID, CustomerNo, Name } Reader in = new FileReader("path/to/file.csv"); Iterable<CSVRecord> records = CSVFormat.RFC4180.builder() .setHeader(Headers.class) .build() .parse(in); for (CSVRecord record : records) { String id = record.get(Headers.ID); String customerNo = ...
GitHub
github.com › apache › commons-csv › blob › master › src › main › java › org › apache › commons › csv › CSVParser.java
commons-csv/src/main/java/org/apache/commons/csv/CSVParser.java at master · apache/commons-csv
public static CSVParser parse(final URL url, final Charset charset, final CSVFormat format) throws IOException { ... * Lexer offset when the parser does not start parsing at the beginning of the source.
Author apache
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-apache-commons-csv
Reading and Writing CSVs in Java with Apache Commons CSV
February 20, 2019 - If you want to read a file that does not contain a header row, want to define your own header, or find indexing confusing, Apache Commons also allows the definition of a header for parsing. Instead of using the .withFirstRecordAsHeader() method when defining the format of the CSV file, you can define a header manually. For example, if you want to avoid referring to the units of measure in the header in our tree data file, you can redefine the header to use your own string values:
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVParser.java.html
CSVParser.java - Apache Commons
If you have already parsed records ... consume a lot of system resources depending on the input. For example, if you're * parsing a 150MB file of CSV data the contents will be read completely into memory.</li> * </ol> * * <h2>Notes</h2> * <p> * The internal parser state is completely ...
Attacomsian
attacomsian.com › blog › read-write-csv-files-apache-commons-csv
How to read and write CSV files using Apache Commons CSV
September 24, 2022 - ID,Name,Email,Country 1,Atta Shah,atta@example.com,PK 2,Alex Jones,alex@example.com,DE 3,Jovan Lee,jovan@example.com,FR 4,Greg Hover,greg@example.com,US · Let us start with the first file that does not contain a header. There are two ways to read this file which are explained below. The simplest way to read a file through Apache Commons CSV is by using the column index to access the value of a record:
Simplesolution
simplesolution.dev › java-read-and-parse-csv-file-using-apache-commons-csv
Read and Parse CSV File in Java using Apache Commons CSV
The following Java example programs to read this CSV file. import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; public class ParseCsvFromPathExample { public static void main(String...
Blogger
javarevisited.blogspot.com › 2015 › 06 › 2-ways-to-parse-csv-files-in-java-example.html
2 Ways to Parse CSV Files in Java - BufferedReader vs Apache Commons CSV Example
August 7, 2021 - countries) { System.out.println("========================"); for (Country country : countries) { System.out.println(country); } System.out.println("========================"); } } Output: Reading from CSV file using BufferedReader and String Split ======================== Country [name=India, capital=New Delhi, currency=INR] Country [name=USA, capital=Washington, currency=USD] Country [name=England, capital=London, currency=GBP] Country [name=Japan, capital=Tokyo, currency=JPY] ======================== Parsing CSV file using CSVParser of Apache commons CSV India New Delhi INR USA Washington USD England London GBP Japan Tokyo JPY You can see output of our program matches with content of our CSV file. So both of our approach is working properly. That's all folks, Enjoy parsing CSV file with Apache commons CSV parser.
CodersLegacy
coderslegacy.com › home › learn java › java csv parser – apache commons
Java CSV Parser - Apache Commons - CodersLegacy
October 6, 2022 - We’ll be using the Apache Commons CSV Parser developed by the Apache Software Foundation for Java. This CSV parser was designed to be a simple and easy way to interact with CSV Files in Java. As you’ll see further on, this Parser was designed with maximum compatibility with different formats and styles. In this article, we’ll cover both how to read and write to and from CSV Files, starting with reading. We’ll be using the following CSV File in the following examples...
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › src-html › org › apache › commons › csv › CSVParser.html
Source code - Apache Commons
If you have already parsed records ... a lot of system resources depending on the input. For example, if you're 137 * parsing a 150MB file of CSV data the contents will be read completely into memory.</li> 138 * </ol> 139 * 140 * <h2>Notes</h2> 141 * <p> 142 * The internal ...
GitHub
github.com › TransmissionZero › Apache-Commons-CSV-Example
GitHub - TransmissionZero/Apache-Commons-CSV-Example: An example of reading and writing CSV files using the Apache Commons CSV library. · GitHub
An example of reading and writing CSV files using the Apache Commons CSV library. - TransmissionZero/Apache-Commons-CSV-Example
Author TransmissionZero
Stack Overflow
stackoverflow.com › questions › 51744690 › apache-commons-csv-parser
java 8 - Apache commons CSV parser - Stack Overflow
List<Record> allRecords = parser.parseAllRecords(new File("/path/to/your.csv")); ... Disclosure: I'm the author of this library. It's open-source and free (Apache 2.0 license)
DZone
dzone.com › coding › java › working with csv files in java using apache commons csv
Working With CSV Files in Java Using Apache Commons CSV
April 30, 2018 - Let's now read the content of the generated CSV file using the following program: import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; public class BasicCsvReader { public static void main(String[] args) throws IOException { BufferedReader reader = Files.newBufferedReader(Paths.get("student.csv")); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader("Student Name", "Fees").withIgnoreHeaderCa
Maven Repository
mvnrepository.com › artifact › org.apache.commons › commons-csv
Maven Repository: org.apache.commons » commons-csv
July 27, 2025 - The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types. ... aar android apache api arm assets build build-system bundle client clojure cloud config cran data database eclipse example extension framework github gradle groovy io ios javascript ...