简体   繁体   中英

ArrayIndexOutOfBoundsException for String.split()

This is the code for reading input from a file which contains student details in the form roll,name,age,street,city,zipcode . Few values among these can be null even.

For the following code, I am getting java.lang.ArrayIndexOutOfBoundsException: 1

Code is as follows-

    BufferedReader br=new BufferedReader(new FileReader(fileName));
    while((line=br.readLine())!=null){

        split_array=line.split("\\,");

        String roll1=split_array[0];
        String name=split_array[1];// This is the line which causes Exception
        String age1=split_array[2];
        String street=split_array[3];
        String city=split_array[4];
        String zip=split_array[5];
    }

If you have empty lines in the middle of the file, you should

if (line.equals(""))
    continue;

or

if (split_array.length <= 1)
     continue;

after calling split()

  • you should use a delimiter to separate each column.
  • Check the length before using the Indexes since you said some data could be missing so sometimes the index will be out of bound.
  • Its always good practice to assume that sometimes the user wouldn't provide the data in the required format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM