所以我有这个 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) ()), '|');
.
此外,我认为没有任何理由将 validEmail
作为数组,我认为它应该只是一个 boolean
。
还有一个建议是使用正则表达式来验证电子邮件,而不是逐个字符地读取电子邮件并进行验证。
关于java - java中的csv文件的电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814226/