While using Super CSV can I get the column number in which there is a validation error?

StackOverflow https://stackoverflow.com/questions/18332027

  •  25-06-2022
  •  | 
  •  

Domanda

I'm using Super CSV for validating a csv file.

I'm getting the row number as listReader.getRowNumber() but is there a way by which i can get the column number in which there is a validation mistake?

È stato utile?

Soluzione

You sure can. The SuperCsvException thrown by Super CSV has a getContext() method, which returns the CsvContext when the exception was thrown (you'll need a try/catch around the call to read()).

This contains lots of useful information, including:

  • The line number (starts at 1). This is the actual line number of the file.
  • The row number (starts at 1). This is not (always) the same as line number (one row can span multiple lines!)
  • The column number (starts at 1)
  • The row source (in this case the List of tokenized Strings for each column, before cell processors are applied)

In addition, you can also call the getUntokenizedRow() method of the CsvReader to get the raw untokenized row of CSV.

For example

ICsvListReader listReader = null;
try {
    listReader = new CsvListReader(new FileReader(CSV_FILENAME),
        CsvPreference.STANDARD_PREFERENCE);

    listReader.getHeader(true); // skip the header

    final CellProcessor[] processors = 
            new CellProcessor[]{new Optional(), new ParseInt()};

    List<Object> row;
    while( (row = listReader.read(processors)) != null ) {
        System.out.println(String.format("lineNo=%s, rowNo=%s, row=%s",
            listReader.getLineNumber(), listReader.getRowNumber(), row));
    }

} catch (final SuperCsvException e){

    // here's what you're after!
    final CsvContext context = e.getContext();
    System.out.println(String.format(
        "something went wrong on lineNo=%s, rowNo=%s, colNo=%s",
        context.getLineNumber(), 
        context.getRowNumber(), 
        context.getColumnNumber()));

} finally {
    if( listReader != null ) {
        listReader.close();
    }
}

Update:

After looking at the code you added, it looks like you want to capture the validation exceptions, not just know the column number. If so, you should take a look at this question.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top