apache-commons-csv - Apache 公共(public) CSV : Avoiding IllegalArgumentException if header does not exist

标签 apache-commons-csv

我有一个包含 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/

相关文章:

java - 使用java在csv中插入空行

java - 使用 apache commons 获取 CSV 文件头

java - 如何使用 FileUtils 从 JUnit Test 中的资源目录读取 csv 文件

java - Apache Commons CSV 框架是否提供内存高效的增量/顺序模式来读取大文件?

java - 模拟 Apache Commons CSV CSVRecord

Java - 使用 Apache.commons.csv 编写 CSV 文件

java - 为什么 Apache Commons CSVParser.getHeaderMap() 总是返回 null?

java - 无法通过 Apache commons csv 读取更多记录

java - Apache Commons CSV 不会忽略缺失的列

java - 将标题行索引传递给 Apache Commons CSV