在Java中防止ArrayIndexOutofBoundsException

时间:2014-03-04 13:51:24

标签: java indexoutofboundsexception

如何在下面的代码中阻止ArrayIndexOutofBoundsException,同时转换数据存储每个记录的标题和值,以便随后准备插入查询。

BufferedReader reader = new BufferedReader(new FileReader("C:\\files\\test.dat"));
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
int lineNumber = 1;
String[] columnName = null;
ArrayList<String[]> value = null; // temp array
String line;
String[] arr;
List<String> headers = null;

while (reader.ready())
    if (!(line = reader.readLine()).isEmpty()) {
        arr = line.split("[\\r\\n]+");

        if (lineNumber == 1) {
            lineNumber++;
            continue;  
        }
        if (lineNumber == 2) {
            headers= Arrays.asList(arr[0].split("\\|"));
            value=new ArrayList<String[]>();
        }
        else
            value.add(arr[0].split("\\|"));// create values

        lineNumber++;
    }

// transform data
for (int i = 1; i < headers.size(); i++) {
    ArrayList<String> ar = new ArrayList<String>();

    for (int j = 0; j < value.size(); j++)
        ar.add(value.get(j)[i]); // <---- Getting error here

    map.put(headers.get(i), ar);
}

System.out.println(map);

}

test.dat有以下数据。在第4条记录上面的代码试图在 Emp sal 之后检索,但没有数据,因此代码失败。

"X"|"Y"|"12345 0000"

"Emp No"|"Emp sal"|"Emp Name"

1|23.4567|"jhon"

2|0.4567|"steve"

3|9.4567|"jhon"

4|123

1 个答案:

答案 0 :(得分:2)

不要假设给定的数组或列表在给定位置总是有一些元素。首先检查容器的尺寸!您期望每行包含与标题行相同数量的元素。因此,在致电value.get(j)[i]之前,请检查value.get(j).length == headers.size()。如果没有,您可以continue或抛出异常。