【问题标题】:OpenCSV - Find out line numberOpenCSV - 找出行号
【发布时间】:2012-09-10 18:07:17
【问题描述】:

我如何知道文件中与 CSVReader 类读取的行相关联的实际行号?假设此类读取的每一行都是文件中的新行,我可以计算行数。问题是 CSV 文件中可能有换行符。因此,例如,拥有 3 个“逻辑”行并不意味着我们在文件中有 3 个“物理”行。我有一个错误报告功能,因此几乎总是报告错误的行号。

任何想法如何确定文件中的真实行号?谢谢!

【问题讨论】:

    标签: csv line-numbers opencsv


    【解决方案1】:

    如果你愿意修改source code,可以加个计数器

    private String getNextLine()
    

    增加两个地方的计数器

    br.readLine();
    

    被调用,并将计数器公开为公共属性。

    如果您不想修改源代码,对于返回的每个 CSV 行,您可以将自己的计数器增加 1 + the sum of the newline characters in the CSV line(可能 OpenCSV 正在将包含换行符的列返回到您的代码中,尽管我没有测试过行为)。如果 A 列有一个换行符,B 列有两个换行符,实际文件应该类似于:

    “这是

    单元格 A","和

    单元格

    B"

    产生 3 个换行符(或 \r\n 序列,取决于您的平台),加上 OpenCSV 返回的 1 行。将计数器增加 4。

    【讨论】:

    • 我试图避免这些事情,但我想这是不可能的,所以我会采取第二种选择。谢谢。
    【解决方案2】:

    如果您愿意将开源 API 切换为 Super CSV(区分物理行和 CSV 行),那么您将有以下 3 种方法可供您使用:

    /**
     * Gets the current position in the file. 
     * The first line of the file is line number 1.
     * 
     * @since 1.0
     */
    int getLineNumber();
    
    /**
     * Returns the untokenized CSV row that was just read 
     * (which can potentially span multiple lines in the file).
     * 
     * @return the untokenized CSV row that was just read
     * @since 2.0.0
     */
    String getUntokenizedRow();
    
    /**
     * Gets the current row number (i.e. the number of CSV records - including the 
     * header - that have been read). This differs from the lineNumber, which is 
     * the number of real lines that have been read in the file. 
     * The first row is row 1 (which is typically the header row).
     * 
     * @since 2.0.0
     */
    int getRowNumber();
    

    【讨论】:

      【解决方案3】:

      您写道,您需要错误报告的行号。
      CsvException 类有一个您可以使用的 getLineNumber 方法。

      当然,这仅在您有异常时才有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 2015-08-25
        • 1970-01-01
        • 2013-02-28
        • 1970-01-01
        • 1970-01-01
        • 2016-05-10
        相关资源
        最近更新 更多