我有一个包含 3 个 header A、B、C 的 CSV 文件。在我的代码中,我使用 CSVReader 的 get 方法来访问这些 header 中的值。如果我使用相同的代码来处理只有 header A、B(而不是 C)的文件,有没有办法让 CSVFormat 避免 get() IllegalArgumentException?
谢谢。
最佳答案
我认为您可以只使用“Header auto detection”并仅在通过 getHeaderMap() 将其检测为 header 时读取“C”列:
try (Reader in = new StringReader(
"A,B,C\n" +
"1,2,3\n")) {
CSVParser records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
System.out.println("A: " + record.get("A"));
System.out.println("B: " + record.get("B"));
System.out.println("C: " + record.get("C"));
}
}
try (Reader in = new StringReader(
"A,B\n" +
"4,5\n")) {
CSVParser records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
System.out.println("A: " + record.get("A"));
System.out.println("B: " + record.get("B"));
if(records.getHeaderMap().containsKey("C")) {
System.out.println("C: " + record.get("C"));
} else {
System.out.println("C not found");
}
}
}
关于apache-commons-csv - Apache 公共(public) CSV : Avoiding IllegalArgumentException if header does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52425013/