class CSVFileParser {
ArrayList<String[]> convertCSVToArrayList(String filePath) {
String line = "";
ArrayList<String[]> rows = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
rows.add(row);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return rows;
}
}
Please help me why its not working. When i try to add 18th index this error come, till 17th its working fine, anyone fix this for me, where I am doing mistake
The comments have the answer, but they're not exactly coherent.
String.split(",", limit)will return an array with length equal to the number of fields found up tolimit(corrected based on a comment below), so if there are 17 commas, it will be an array with index [0] to [17], length 18. Iflimitis 0 or omitted, any empty fields at the end will be omitted. The file delivery.csv has headers with 21 fields, but not all lines are the same length. That's the first problem, you should specify the expected limit, and all lines should have 20 commas (any short lines should have empty fields at the end like "abc,def,qrs,tuv,,,").On the other hand, your software should also be able to deal with errors like this. If you use a package that's been developed for reading CSV files, that's probably already been done. If you want to use
split()in this way, you have to check the length of the returned array before trying to access it.Also you might need to validate the CSV file in other ways, it might omit fields in the middle (e.g. instead of "abc,,ghi" it might have "abc,ghi"). If that's the case, try to get a file that's formatted correctly, or you might need to encode special cases to correct these problems.
Also, make sure the file doesn't have cases like "
abc,"d,f",ghi" or "abc,d\,f,ghi" which have commas in the data. CSV parsing packages can deal with those cases, it will be harder for you to add code to handle that always correctly.