【问题标题】:email validation from csv file in java来自java中的csv文件的电子邮件验证
【发布时间】: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


【解决方案1】:

首先,你需要告诉 CSVReader 你的分隔符默认是|,它需要, 类似于new CSVReader(new FileReader(fileName.getPath()), '|');

另外,我认为没有任何理由将validEmail 作为一个数组,我认为它应该只是一个boolean

另一个建议是使用正则表达式来验证电子邮件,而不是逐个字符地读取它并进行验证。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2015-07-10
    • 1970-01-01
    • 2011-12-01
    • 2010-09-14
    相关资源
    最近更新 更多