FastCSV icon indicating copy to clipboard operation
FastCSV copied to clipboard

Allow early access to the header when using NamedCsvRecord

Open osiegmar opened this issue 9 months ago • 1 comments

When reading a file using NamedCsvRecord, the first record is stored internally as the header and used for name-based field mapping. The header itself is not returned as a record. As a consequence, it is not possible to access the header when the file only contains the header but no data.

It should be possible to access the header even when the file only consists of a header.

Discussed in https://github.com/osiegmar/FastCSV/discussions/146

Originally posted by xavier-figueroa June 16, 2025 I havent seen any easy way to get the existing headers for a file. It would be great to get a list/map with all the headers (first row)

osiegmar avatar Jun 18 '25 08:06 osiegmar

This is how the feature is going to work in FastCSV 4:

Path file = Path.of("test.csv");
NamedCsvRecordHandler rh = NamedCsvRecordHandler.of(c -> c.returnHeader(true));
try (CloseableIterator<NamedCsvRecord> csv = CsvReader.builder().build(rh, file).iterator()) {
    if (!csv.hasNext()) {
        throw new IllegalStateException("No records found");
    }

    List<String> header = csv.next().getHeader();

    if (!csv.hasNext()) {
        throw new IllegalStateException("No data records found after header. Header: " + header);
    }

    while (csv.hasNext()) {
        NamedCsvRecord dataRecord = csv.next();
        // ...
    }
}

osiegmar avatar Jun 18 '25 08:06 osiegmar

feature released

osiegmar avatar Jun 22 '25 14:06 osiegmar