1

I am trying to read a big csv file in a while loop. But when I run the code I got java.lang.ArrayIndexOutOfBoundsException: 5 Is there a step I am missing?

  String csvFileToRead = "C:/automation/test.csv"; 

  BufferedReader br = null; 

  String line = "";  
  String splitBy = ",";  

  try {  boolean firstLine = true;
      br = new BufferedReader(new FileReader(csvFileToRead));  

      while ((line = br.readLine()) != null ) {       

       if (firstLine) {
           firstLine = false;
                continue;}

       String[] id = line.split(splitBy);
    String replace = id[5].replace("\"", "");



    String cardNo = id[5].replace("\"", "");


    String fname = id[8].replace("\"", "");
    String name = driver.findElement(By.id("bnxczxc")).getAttribute("value");


    if (name.equals(fname)) { 
        //code
    }
    else {
        //code
    }


   }  

  } catch (FileNotFoundException e) {  
   e.printStackTrace();  
  } catch (IOException e) {  
   e.printStackTrace();  
  } finally {  
   if (br != null) {  
    try {  
     br.close();   

    }
    catch (IOException e) {  
     e.printStackTrace();}}}     
1
  • Some of you content of the file might not have that much commas as you have coded.Show us the content of the file Commented Feb 17, 2015 at 7:17

3 Answers 3

1

You're eventually hitting a line in your CSV file that doesn't have at least 6 values in it, so this line is throwing an error:

String replace = id[5].replace("\"", "");

I would suggest a check such as:

if(id.length > 0)
{
// Do the stuff you're trying to do
}
else
{
// Log or print error
}

What I expect you'll find if you troubleshoot further is that your program is attempting to read the last line of the file which would be blank.

Sign up to request clarification or add additional context in comments.

Comments

0

You get the exception here id[5] if your line has only 4 attributes. Check id.length before you try to get the 5th attribute. And remember that arrays are zero beased in java.

Comments

0

When you are specifying array index like id[5], there is the exception because id array doesn't contain elements till index 5. If the size of id array is 5, then you have to access its last element by using id[4] as array length starts from 0. PS: First System.out.println(id.length) to check the length of id array. Then you will have the overall idea of this exception.

Hope it may help.

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.