I have a CSV file with 8 columns:
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 ?
The version of split you're invoking removes trailing empty strings.
Trailing empty strings are therefore not included in the resulting array
Your first row has date_sold
column empty. Try invoking split like this instead:
String[] cols = line.split(",", -1);