3

I have a CSV file that contains 3 headers A, B, C. In my code I use CSVReader's get method to access the values in these headers. Is there a way I can CSVFormat to avoid a get() IllegalArgumentException if I use the same code to process a file with only headers A, B (and not C)?

Thanks.

1 Answers1

3

I think you can just use the "Header auto detection" and read column "C" only if it is detect as header via getHeaderMap():

    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");
            }
        }
    }
centic
  • 15,565
  • 9
  • 68
  • 125