Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons CSV: Avoiding IllegalArgumentException if header does not exist

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.

like image 876
Milton Ezeh Avatar asked Nov 19 '25 07:11

Milton Ezeh


1 Answers

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");
            }
        }
    }
like image 162
centic Avatar answered Nov 22 '25 05:11

centic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!