如何在java中获取csv文件的行索引

时间:2016-11-21 07:21:52

标签: java arrays csv

我的程序是验证输入代码是否为空。条件是如果输入的代码编号(通过csv文件)继续,如果代码编号为空,则显示错误消息。 "代码编号为空行:__"。 我的问题是如何打印代码编号为空的行的索引。

这是我的样本数据(csv):

CRITERIA  CODE  NAME  AGE ADDRESS
ADD       0001  JOHN  21  USA
ADD             MICH  16  EUR
ADD             ALI   11  PHL

错误信息应为:

"The code number is empty in line 2."
"The code number is empty in line 3."

这是我目前的计划:

private static String[] sNextLine2; 
public static Map<String,Employee> getChanges
( String sFileName, Map<String, Employee> mEmployeeList )
throws IOException {
                                    //Read_File
    setReader2(new CSVReader(new FileReader(sFileName)));
    while ((sNextLine2 = reader2.readNext()) != null) { 
    switch(sNextLine2[0]) {
        case "ADD":         
            if(sNextLine2[1].isEmpty()) {
                System.out.println("The code number is empty in line" + lineNumber); //how to get that line number

            } else if (mEmployeeList.containsKey(sNextLine2[1]))
            {
                System.out.println("Data already exist");
            }
            else
            {
                mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
                        sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
                        sNextLine2[6], sNextLine2[7], sNextLine2[8]));
            }

            break;
    } 

我希望有人会帮助我。谢谢!

1 个答案:

答案 0 :(得分:1)

你可以添加一个计数器,每.readNext()递增一次,如果有错误就打印出来

 int counter=0;
 while ((sNextLine2 = reader2.readNext()) != null) { 
    counter++;
    switch(sNextLine2[0]) {
        case "ADD":         
            if(sNextLine2[1].isEmpty()) {
                System.out.println("The code number is empty in line" + counter); //how to get that line number

            } else if (mEmployeeList.containsKey(sNextLine2[1]))
            {
                System.out.println("Data already exist");
            }
            else
            {
                mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
                        sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
                        sNextLine2[6], sNextLine2[7], sNextLine2[8]));
            }

            break;
    }