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 Answer 1

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");
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.