-
| 
         Hi, I tested the NamedCSVReader. It works fine if the header is on line 1 of the CSV file. But if the header is on line 2 or any other line number than 1 it does not work. Is it possible to define a starting position e.g. header starts on line 3? Thank you  | 
  
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
| 
         As defined in section 2.3 of RFC 4180: 
 In section 2.1.3 of current DRAFT RFC 4180-bis this is updated: 
 followed by section 2.1.8: 
 This is what the NamedCsvReader supports: String csv = "# commented line\nheader\nbody\n";
NamedCsvReader.builder()
    .skipComments(true)
    .build(csv)
    .forEach(row -> System.out.println(row.getField("header")));In order to skip non-RFC-compliant CSV data at the beginning you could use a BufferedReader: BufferedReader br = new BufferedReader(new StringReader(csv));
// skip arbitrary (non-CSV) data until line break
br.readLine();
NamedCsvReader.builder()
    .build(br)
    .forEach(row -> System.out.println(row.getField("header"))); | 
  
Beta Was this translation helpful? Give feedback.
-
| 
         Using FastCSV 3 (soon to be released) this would work: String csvData = """
    some arbitrary data here
    ...some other here
    header A,header B
    field A,field B
    """;
CsvReader csvReader = CsvReader.builder().build(csvData);
// Read data until you found the actual header
List<String> headerToUse = null;
for (CsvRecord csvRecord : csvReader) {
    if (csvRecord.getField(0).equals("header A")) {
        headerToUse = csvRecord.getFields();
        break;
    }
}
if (headerToUse == null) {
    throw new IllegalStateException("No header found");
}
// Initialize the NamedCsvReader with the header to use
NamedCsvReader namedCsvReader = NamedCsvReader.from(csvReader, headerToUse);
// Use the header / NamedCsvReader
for (NamedCsvRecord namedCsvRecord : namedCsvReader) {
    System.out.println(namedCsvRecord.getField("header A"));
} | 
  
Beta Was this translation helpful? Give feedback.
As defined in section 2.3 of RFC 4180:
In section 2.1.3 of current DRAFT RFC 4180-bis this is updated:
followed by section 2.1.8:
This is what the NamedCsvReader supports:
In order to skip non-RFC-compliant CSV data at the beginning you could use a BufferedReader: