ArrayIndexOutOfBoundsException when splitting the line of a text file

155 views Asked by At

I'm trying to spit this text file:

asdf;asdf;asdf;N/A;N/A;N/A;N/A;N/A;N/A;N/A;N/A

Just so you know. there is no empty line at the bottom of it. That's all there is.

The piece of code that does this job is this.

try{
                s = fIN.readLine();
                while(s != null){
                    Parts = s.split(";");
                    NameFile = Parts[0];
                    IngredientFile[1] = Parts[1];
                    QuantityFile[1] = Parts[2];
                    IngredientFile[2] = Parts[3];
                    QuantityFile[2] = Parts[4];
                    IngredientFile[3] = Parts[5];
                    QuantityFile[3] = Parts[6];
                    IngredientFile[4] = Parts[7];
                    QuantityFile[4] = Parts[8];
                    IngredientFile[5] = Parts[9];
                    QuantityFile[5] = Parts[10];
                    list1.add(NameFile + "\n");
                    for(i=1; i<6; i++){
                        list1.add(" " + IngredientFile[i] + "" + QuantityFile[i] + "\n");
                    }
                    s = fIN.readLine();
                }
            }catch(IOException e){
                list1.add(" ERROR READING FILE. \n");
            }

It's throwing the error ArrayIndexOutOfBoundsException: 1 on line 45 which is this

IngredientFile[1] = Parts[1];

Apparently it's the Parts array which is giving me this but that can't be right because I declared it with the size of 1000 just for safety.

public String[] Parts = new String[1000];

Anyone have any ideas what's going on?

1

There are 1 answers

0
ingrid.e On

You should check the length of Parts before making assignments to make sure it split correctly or throw an exception if not. In your case, the line probably didn't have any ";" separator.

also, you could eliminate the case where you have an empty line or some weird characters.

    if (!s.isEmpty() && !s.trim().equals("") && !s.trim().equals("\n")){
//split
}