java中csv文件的电子邮件验证
我有一个CSV文件,它包含一系列字段,其中一个是电子邮件字段。输入的一些电子邮件是空的,其他的格式不正确。有点像这样:java中csv文件的电子邮件验证,java,email,csv,indexoutofboundsexception,opencsv,Java,Email,Csv,Indexoutofboundsexception,Opencsv,我有一个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;
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();
}
}
我真的不知道它为什么会抛出这个错误,因为我试图访问电子邮件字段,这是CSV文件的第四个字段。为什么它会抛出此异常,我如何修复它以避免自动抛出它?首先,您需要告诉CSVReader您的分隔符是
。
默认情况下,它需要,
类似于新CSVReader(新文件阅读器(fileName.getPath()),“|”的内容代码>
另外,我不认为有任何理由将validEmail
作为一个数组,我认为它应该只是一个布尔值
还有一个建议是使用正则表达式来验证电子邮件,而不是逐字符读取并验证。首先,您需要告诉CSVReader
您的分隔符是
,默认情况下,它需要,
新的CSVReader(新的文件阅读器(FileReader)(fileName.getPath()),“|”)代码>。当您执行System.out.println(row.length)时,会得到什么?
if(!row[3].isEmpty()){
...
}