简体   繁体   English

String.split() 的 ArrayIndexOutOfBoundsException

[英]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 .这是从包含学生详细信息的文件中读取输入的代码,格式为roll,name,age,street,city,zipcode Few values among these can be null even.其中很少有值可以为null

For the following code, I am getting java.lang.ArrayIndexOutOfBoundsException: 1对于以下代码,我收到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()调用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.假设有时用户不会以所需格式提供数据总是好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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