【问题标题】:Apache Commons CSV: Avoiding IllegalArgumentException if header does not existApache Commons CSV:如果标头不存在,则避免 IllegalArgumentException
【发布时间】:2019-02-24 18:12:54
【问题描述】:

我有一个 CSV 文件,其中包含 3 个标头 A、B、C。在我的代码中,我使用 CSVReader 的 get 方法来访问这些标头中的值。如果我使用相同的代码来处理只有标题 A、B(而不是 C)的文件,有没有办法 CSVFormat 来避免 get() IllegalArgumentException?

谢谢。

【问题讨论】:

    标签: apache-commons-csv


    【解决方案1】:

    我认为您可以只使用“Header auto detection”并仅在通过 getHeaderMap() 将其检测为标题时读取“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");
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2016-07-16
      • 2023-03-05
      相关资源
      最近更新 更多