1

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);
    }
4
  • all entries in your file does not have comma. Please paste the contents of your file If its ok. Check the length of the nextRecord array before you access nextRecord[index] Commented Jul 9, 2021 at 6:45
  • you can avoid it by checking if line is not empty Commented Jul 9, 2021 at 6:47
  • try to use readNextSilently and check that nextRecord != null && nextRecord.length > 1 Commented Jul 9, 2021 at 6:48
  • Yeah checking the length solved the issue. Thanks everyone Commented Jul 9, 2021 at 7:06

1 Answer 1

2

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.