【发布时间】:2014-09-12 18:05:08
【问题描述】:
所以我有这个 CSV 文件,其中包含一堆字段,其中一个是电子邮件字段。一些已输入的电子邮件是空的,而另一些则格式不正确。有点像这样:
Entry|First Name|Last Name|Email|Sign-up Date
1|Mike|Smith|mike.smith@gmail.com|2004-08-08
2||||2006-06-12
3|Perry|File|public|2010-09-14
我在这里检测电子邮件是否有效的代码如下:
private boolean[] validEmail;
public void setValidEmail(File fileName){
Log log = LogFactory.getLog(LoadValidEmail.class);
try{
CSVReader csvReader = new CSVReader(new FileReader(fileName.getPath()));
String[] row = null;
char[] email = null;
int count = 0;
while(!(row = csvReader.readNext()).equals(null)){
if(count!=0){
if(!row[3].isEmpty()){
email = row[3].toCharArray();
for(int i = 0; i < email.length; i++){
if(email[i] == '@'){
validEmail[count-1]=true;
break;
}
}
if(!validEmail[count-1]){
validEmail[count-1] = false;
}
}else{
validEmail[count-1] = false;
}
}
count++;
}
}catch(FileNotFoundException e){
log.info("File could not be found, make sure directory is correct and try again");
e.printStackTrace();
}catch(IOException e){
log.info("File could not read next line, make sure file contains information and try again");
e.printStackTrace();
}catch(IndexOutOfBoundsException e){
log.info("The array has gone out of bounds, this is not the row you are looking for");
e.printStackTrace();
}
}
每次运行时都会抛出 IndexOutOfBoundsException 并在该行直接崩溃:
if(!row[3].isEmpty()){
...
}
我真的不知道为什么会抛出这个错误,因为我正在尝试访问电子邮件字段,这是 CSV 文件的第四个字段。为什么会抛出这个异常,我该如何解决它以不自动抛出它?
【问题讨论】:
-
首先,你需要告诉
CSVReader你的分隔符默认是|,它需要,new CSVReader(new FileReader(fileName.getPath()), '|');。 -
当你做 System.out.println(row.length) 你得到什么?
标签: java email csv indexoutofboundsexception opencsv