问题描述
这可能非常简单,但我一直无法找到执行此操作的选项。我正在尝试使用 Apache Commons CSV 读取文件以供以后验证。有问题的 CSV 作为输入流提交,它似乎在读取文件时向文件添加了一个附加列,其中包含行号。如果可能,我希望能够忽略它,因为标题行不包含会导致错误的数字。 InputStream 中是否已有选项可以执行此操作,还是我必须设置某种后期处理?
我使用的代码如下:
public String validateFile(InputStream filePath) throws Exception{
System.out.println("Sending file to reader");
System.out.println(filePath);
InputStreamReader in = new InputStreamReader(filePath);
//CSVFormat parse needs a reader object
System.out.println("sending reader to CSV parse");
for (CSVRecord record : CSVFormat.DEFAULT.withHeader().parse(in)) {
for (String field : record) {
System.out.print("\"" + field + "\",");
}
System.out.println();
}
return null;
}
使用 withHeader()
时,我最终遇到以下错误:
java.lang.IllegalArgumentException: A header name is missing in [,Employee_ID,Department,Email]
我不能简单地跳过它,因为我需要对标题行进行一些验证。
"Employee_ID","Department","Email"
"0123456","Department of Hello World","John.Doe@gmail.com"
编辑:此外,最终目标是验证以下内容:
解决方法
较新版本的 Commons-CSV 有空标题的问题。 也许这里也是这种情况? 您刚刚提到“没有空单元格值”不确定这是否也包括标题...
另见:https://issues.apache.org/jira/browse/CSV-257
设置 .setAllowMissingColumnNames(true)
对我有用。
final CSVFormat csvFormat = CSVFormat.Builder.create()
.setHeader(HEADERS)
.setAllowMissingColumnNames(true)
.build();
final Iterable<CSVRecord> records = csvFormat.parse(reader);