'Java CSVParser gets empty after reading it

In the snippet below I try to read an excel file by using the CSVParser from the Apache Commons library. The question is why records.getRecords(); makes the list of records empty. How should I be aware of this behavior?

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class ReadCSV {

    public ReadCSV() {
    }

    /* Define headers as enum */
    enum HEADER {
        ID, NAME, AGE
    }

    public List<List<String>> ReadCSVToList(String csvPath) throws IOException, HighBalanceException {
        List<List<String>> csvList = new ArrayList<>();
        try {


            Reader reader = new FileReader(csvPath);
            CSVParser  records = CSVFormat.DEFAULT.withHeader(HEADER.class).parse(reader);
            List<CSVRecord> records1 = records.getRecords();
            System.out.println(records1.size()); // 2
            List<CSVRecord> records2 = records.getRecords();
            System.out.println(records2.size()); // 0


Solution 1:[1]

As you can read in the official docs: CSVParser#getRecords

The returned content starts at the current parse-position in the stream.

In your first call of getRecords, the parsing position is at the beginning of the stream. When you call it the second time, the stream end is already reached.

In general, I would always recommend you to start with the docs. Often, such questions can be easily answered with just little reading. If there are still confusing aspects, the community is of course happy to help you further.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1