当发生特定条件时,如何从使用 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();
}
}
最佳答案
为循环设置一个计数器,以在解析 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();
}
}
关于java - 检测 CSV 文件中出现的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820095/