OpenCSV - 找出行号

时间:2012-09-10 18:07:18

标签: csv line-numbers opencsv

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

如何确定文件中的实际行号?谢谢!

3 个答案:

答案 0 :(得分:0)

如果您愿意修改source code,可以添加计数器

private String getNextLine()

的两个地方增加计数器
br.readLine();
调用

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

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

  

“这是

     

Cell A“,”和

     

细胞

     

B“

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

答案 1 :(得分:0)

如果您愿意将开源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();

答案 2 :(得分:0)

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

当然,这仅在出现异常时有效。

相关问题