【问题标题】:Detect Line Number of Occurrences In CSV File检测 CSV 文件中出现的行数
【发布时间】:2013-02-11 20:17:24
【问题描述】:

如何从使用 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();
    }
}

【问题讨论】:

  • 你知道如何将 int linecounter 加一吗?

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


【解决方案1】:

为您的循环设置一个计数器,以便在您解析 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();
    }
}

【讨论】:

    【解决方案2】:

    怎么样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-04
      • 2021-12-13
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多