2

I'm using Univocity library to parse CSV and it works perfectly, but I need a way to detect if the file being parsed has less columns than required

For example, if I'm expecting a 3 columns file, with columns mapped to [H1,H2,H3] then I received a file (which has no headers) that looks like

V1_H1,V1_H2
V2_H1,V2_H2

When using

record.getString("H3");

this would return null, instead, I need this file to either fail to be parsed or I can check if it misses a column and stop processing it

Is there any way to achieve this?

Safaa Selim
  • 106
  • 4

2 Answers2

2

So since my main issue here is to make sure that the headers count is the same as the number of columns provided in the CSV file, and since I'm using an iterator to iterate over records, I've added a check like:

CsvParser parser = new CsvParser(settings);
ResultIterator<Record, ParsingContext> iterator = parser.iterateRecords(inputStream).iterator();
if(iterator.getContext().parsedHeaders().length != settings.getHeaders().length){
    throw new Exception("Invalid file");
}

It's working for me, not sure if there is a better way to do it.

Safaa Selim
  • 106
  • 4
1

I've watched Univocity documentation and I've found here that there is a way to add annotations to the destination objects you are going to generate from the CSV input

    @Parsed
    @Validate
    public String notNulNotBlank; //This should fail if the field is null or blank

    @Parsed
    @Validate(nullable = true)
    public String nullButNotBlank;

    @Parsed
    @Validate(allowBlanks = true)
    public String notNullButBlank;

This will also help you to use the objects instead of having to work with fields.

Hope that helps :-)

Théo camb.
  • 198
  • 1
  • 5
  • thanks a lot Theo, this would work but my case is more dynamic, where the fields/headers are part of the input Which means that my parser would parse any CSV file given the file and headers mapping – Safaa Selim Jun 28 '19 at 10:02