使用 Apache Commons CSV 进行解析,但不会忽略丢失的列并引发异常。
使用此示例数据:
name age
Ali 35
John 25
Vahid 75
下面的代码record.get(DataColumns.surname)
抛出java.lang.IllegalArgumentException: Mapping for surname not found, expected one of [name, surname, age]
. 我需要它返回 null、可选或默认值。有什么选择吗?我知道这是可能的,record.toMap().get(DataColumns.surname.name())
但它的性能不会很好:
...
enum DataColumns { name, surname, age }
...
Reader in = new BufferedReader(new FileReader(fileName));
try (CSVParser records = CSVFormat.TDF
.withDelimiter(' ')
.withIgnoreSurroundingSpaces()
.withAllowDuplicateHeaderNames(false)
.withIgnoreHeaderCase()
.withTrim()
.withHeader(DataColumns.class)
.withFirstRecordAsHeader()
.withSkipHeaderRecord()
.withAllowMissingColumnNames(false)
.withIgnoreEmptyLines()
.parse(in)) {
for (CSVRecord record : records) {
String name = record.get(DataColumns.name);
String surname = record.get(DataColumns.surname);
Short age = Short.valueOf(record.get(DataColumns.age));
}
}
...