3

I am trying to convert all rows in a CSV file into a java bean using openCSV.Each row has 21 columns in my file separated with pipe symbol(|).But getting null pointer exception with this code.rows in csv file include empty cells also.I am not able to figure out where is the error.can any one help me out

package com.alu.mdf.testsuite.sure;
import java.io.FileReader;
import java.util.List;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;

//import com.alu.mdf.test.common.Person;

    public class CSVExplorer {

        @SuppressWarnings({"rawtypes", "unchecked"})
        public static void main(String[] args) throws Exception
        {
            CsvToBean csv = new CsvToBean();

            String csvFilename = "TestCaseConfigurationFiles/application.csv";
            //CSVReader csvReader = new CSVReader;
            CSVParser csvParser=new CSVParser('|');
            CSVReader reader = new CSVReader(new FileReader(csvFilename),1,csvParser);



            //Set column mapping strategy
            List list = csv.parse(setColumMapping(), reader);

            for (Object object : list) {
                SUREDataBean SUREDataBean = (SUREDataBean) object;
                System.out.println(SUREDataBean);
            }
        }

        @SuppressWarnings({"rawtypes", "unchecked"})
        private static ColumnPositionMappingStrategy setColumMapping() throws Exception
        {
            ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
            strategy.setType(SUREDataBean.class);
            //strategy.createBean();
            String[] columns = new String[] {"InputDataStartIdentifier","EntityType","Operation","IncludeId","IdValue","AssociatedResource","SearchQueryForGETRequest/ParametersForPUTRequest","PayloadLocation","TestCaseName","Description","userName","password","InputDataEndIdentifier","ValidationDataStart","ExpectedStatusCode","VerficationParameters","Method","class","Prerequisites","Group","ValidationDataEnd"};
            System.out.println(columns.length);
            strategy.setColumnMapping(columns);
            return strategy;
        }

    }

Here is error stack trace:

Exception in thread "main" java.lang.RuntimeException: Error parsing CSV! at com.opencsv.bean.CsvToBean.parse(CsvToBean.java:95) at com.opencsv.bean.CsvToBean.parse(CsvToBean.java:75) at com.alu.mdf.testsuite.sure.CSVExplorer.main(CSVExplorer.java:28) Caused by: java.lang.NullPointerException at com.opencsv.bean.CsvToBean.processLine(CsvToBean.java:123) at com.opencsv.bean.CsvToBean.processLine(CsvToBean.java:101) at com.opencsv.bean.CsvToBean.parse(CsvToBean.java:91) ...

1 Answers1

0

I think you'll have less trouble with uniVocity-parsers. It is also way faster than OpenCSV. To use it, first annotate your bean:

class SUREDataBean {

    @NullString(nulls = { "?", "-" }) // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @Parsed(defaultNullRead = "0") // if a value resolves to null, it will be converted to the String "0".
    private Integer quantity; // The attribute name will be matched against the column header in the file automatically.

    @Trim
    @LowerCase
    @Parsed
    private String comments;
    ...

}

To parse:

BeanListProcessor<SUREDataBean> rowProcessor = new BeanListProcessor<SUREDataBean>(SUREDataBean.class);

CsvParserSettings parserSettings = new CsvParserSettings();
settings.getFormat().setDelimiter('|');
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);

//Parsing is started here.
//this submits all rows parsed from the input to the BeanListProcessor
parser.parse(new FileReader(new File("/examples/bean_test.csv"))); 

List<SUREDataBean> beans = rowProcessor.getBeans();

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

josliber
  • 43,891
  • 12
  • 98
  • 133
Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29