检测CSV文件中的行数

时间:2013-02-11 20:17:25

标签: java parsing csv file-io conditional-statements

如何从使用OpenCSV库解析的文件中获取行号?我希望用户在CSV文件中使用行号警告用户,只要在该行上检测到可能有错误的值。

这是一段代码,我将文件解析为字符串数组:

try 
{
    CSVReader reader = new CSVReader(new FileReader(filePath), ',');

    // Reads the complete file into list of tokens.
    List<String[]> rowsAsTokens = null;

    try 
    {
        rowsAsTokens = reader.readAll();
    } 

    for(String[] row: rowsAsTokens) 
    {
        //Check for conditions within CSV file
    }

    catch (IOException e1)
    {
        e1.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:2)

为您的循环设置一个计数器,以便在解析CSV时计算行号。

try 
{
    CSVReader reader = new CSVReader(new FileReader(filePath), ',');

    // Reads the complete file into list of tokens.
    List<String[]> rowsAsTokens = null;

    int lineNum = 0;

    try 
    {
        rowsAsTokens = reader.readAll();
    } 

    for(String[] row: rowsAsTokens) 
    {
        lineNum++; // increment the line number
        //Check for conditions within CSV file
        if (ERRONEOUS VALUE) {
            // save the lineNum. possibly to an array or a string. whatever you need
        }
    }

    catch (IOException e1)
    {
        e1.printStackTrace();
    }
}

答案 1 :(得分:0)

怎么样:

   int line = 0;
   for(String[] row: rowsAsTokens) 
   {

        //Check for conditions within CSV file
        if (isErro) {
            String errMsg = "error in line: " + line;
            // output errrMsg;
        }
        line++;
   }