Search code examples
javacsvparsingopencsv

How to read csv file without header using opencsv?


I do know the header, but the header is parsed separately. I am using a pojo with annotations and setting it as type.

My code looks like this:

 CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
                .withSeparator(SEPERATOR)
                .withIgnoreLeadingWhiteSpace(true)
                .withType(MyObject.class)
                .build();

When I iterate, I get MyObject with all null values. MyObject is the pojo with fields annotated with column names.

Is there a way to set headers in opencsv?


Solution

  • As I mentioned in my last comment, I ended up implementing a custom strategy to fix my issue.

    public class BlahMappingStrategy extends HeaderColumnNameMappingStrategy {
    List<String> headerList;
    
    public BlahMappingStrategy(List<String> headerList) {
        this.headerList = headerList;
    }
    
    @Override
    public void captureHeader(CSVReader reader) throws IOException, CsvRequiredFieldEmptyException {
        if (this.type == null) {
            throw new IllegalStateException(ResourceBundle.getBundle("opencsv", this.errorLocale).getString("type.unset"));
        } else {
            String [] header = headerList.toArray(new String[headerList.size()]);
            this.headerIndex.initializeHeaderIndex(header);
        }
    }
    

    }

    That is all that was needed.