我尝试读取.csv文件并将每列保存到数组中时出现异常问题。 虽然看起来很长的程序,但事实并非如此。我只有15个不同的阵列。Java:读取.csv文件并保存到数组中
这是例外 “异常在线程 ”主“ java.lang.ArrayIndexOutOfBoundsException:2” 的行中
部门[I] = dataArray中[2];
有什么我可以做的吗?
BufferedReader CSVFile =
new BufferedReader(new FileReader("Sub-Companies.csv"));
String dataRow = CSVFile.readLine();
// Read the number of the lines in .csv file
// i = row of the .csv file
int i = 0;
while (dataRow != null){
i++;
dataRow = CSVFile.readLine();
}
System.out.println(i);
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println();
// Save into arrays
customer_id = new String[i];
company_name = new String[i];
department = new String[i];
employer = new String[i];
country = new String[i];
zipcode = new String[i];
address = new String[i];
city = new String[i];
smth1 = new String[i];
smth2 = new String[i];
phone_no1 = new String[i];
phone_no2 = new String[i];
email = new String[i];
website = new String[i];
customer_no = new String[i];
// Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
int j;
int counter;
i = 0;
// Read the file again to save the data into arrays
BufferedReader CSV =
new BufferedReader(new FileReader("Sub-Companies.csv"));
String data = CSV.readLine();
while (data != null){
String[] dataArray = data.split(";");
for (String item:dataArray) {
customer_id[i] = dataArray[0];
company_name[i] = dataArray[1];
department[i] = dataArray[2];
employer[i] = dataArray[3];
country[i] = dataArray[4];
zipcode[i] = dataArray[5];
address[i] = dataArray[6];
city[i] = dataArray[7];
smth1[i] = dataArray[8];
smth2[i] = dataArray[9];
phone_no1[i] = dataArray[10];
phone_no2[i] = dataArray[11];
email[i] = dataArray[12];
website[i] = dataArray[13];
customer_no[i] = dataArray[14];
}
//System.out.print(address[i] + "\n");
data = CSV.readLine(); // Read next line of data.
i++;
}
预先感谢您!
某些数据是“E3B3C5EB-B101-4C43-8E0C-ADFE76FC87FE;”Var Welk“Inh。Kar; NULL; NULL; DE; 16278; Rotr 3;Angermènde; NULL; NULL; 03331/354348-0; 0343331 /364548-15;[email protected];http://www.adss.com;ipo241“,但可能有所不同(更小或更大)。
为什么重新发明轮子?使用像Super CSV或我最喜欢的opencsv这样的CSV解析库。 – dnault
引发该错误以指示已使用非法索引访问数组。该索引大于或等于数组的大小。 –
这会帮助我防止异常吗?我想的东西尝试,赶上,但问题是,我想确保数据正确保存 –