Search code examples
javacsvopencsv

Array Out of Bounds error while Reading 2 Column Csv File using OpenCsv


I am reading a 2 column CSV using opencsv library and I want to put those 2 columns as key-value pairs in a map. However, I am getting Array Index out of bounds exception whenever there is an empty line in CSV. Is there any way I can avoid that? This is my code:

    Map<String, String> map = new HashMap<>();
    CSVReader csvReader;
    try (FileReader filereader = new FileReader(path)) {
        csvReader = new CSVReader(filereader);
        String[] nextRecord;
        while ((nextRecord = csvReader.readNext()) != null) {
            if (nextRecord[0] != null && nextRecord[1] != null) {
                map.put(nextRecord[0], nextRecord[1]);
            }
        }

    } catch (Exception e) {
        System.out.print(e);
    }

Solution

  • array of nextRecord might be empty, so you need to check the length before indexing it

    change

    if(nextRecord[0]!=null && nextRecord[1]!=null){
         map.put(nextRecrod[0],nextRecord[1]);
    }
    

    to

    if(nextRecord.length ==2 && nextRecord[0]!=null && nextRecord[1]!=null){
         map.put(nextRecrod[0],nextRecord[1]);
    }