首页 > 解决方案 > Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 for correctly indexed array

问题描述

I have a CSV file with 8 columns:

enter image description here

I have put each column into an array with the following code

public static void main(String args[]) {

    List<String> wholefile = new ArrayList<String>();
    List<String> id = new ArrayList<String>();
    List<String> property_address = new ArrayList<String>();
    List<String> first_name = new ArrayList<String>();
    List<String> last_name = new ArrayList<String>();
    List<String> email = new ArrayList<String>();
    List<String> owner_address = new ArrayList<String>();
    List<String> price = new ArrayList<String>();
    List<String> date_sold = new ArrayList<String>();


    Path filepath = Paths.get("./data.csv");


    try {

      BufferedReader br = new BufferedReader(new FileReader("./data.csv"));
       String line;
       while ((line = br.readLine()) != null) {
         wholefile.add(line);
         String[] cols = line.split(",");
         id.add(cols[0]);
         property_address.add(cols[1]);
         first_name.add(cols[2]);
         last_name.add(cols[3]);
         email.add(cols[4]);
         owner_address.add(cols[5]);
         price.add(cols[6]);
       }
      System.out.println(id);
      System.out.println(property_address);
      System.out.println(first_name);
      System.out.println(last_name);
      System.out.println(email);
      System.out.println(owner_address);
      System.out.println(price);


   } catch (IOException e) {
       e.printStackTrace();
   }
}

when I run this code I get the following output:

id = [id,1,2,3,4,5...]
property_address = [property address, 94032 Mockingbird Alley, 293 Haas Lane, 75 Ruskin Lane...]

and so on just like I expect!

However when I add

date_sold.add(cols[7]);

I get a error that

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7

I do not know why as there are 8 columns and I have started indexing from 0. Is there something wrong with my while statement ?

标签: javaarrayscsvbufferedreaderindexoutofboundsexception

解决方案


您正在调用的split版本会删除尾随的空字符串。

因此,尾随空字符串不包含在结果数组中

您的第一行的date_sold列是空的。尝试像这样调用 split :

String[] cols = line.split(",", -1);

推荐阅读