Search code examples
javaopencsv

How to read from particular header in opencsv?


I have a csv file. I want to extract particular column from it.For example: Say, I have csv:

id1,caste1,salary,name1
63,Graham,101153.06,Abraham
103,Joseph,122451.02,Charlie
63,Webster,127965.91,Violet
76,Smith,156150.62,Eric
97,Moreno,55867.74,Mia
65,Reynolds,106918.14,Richard

How can i use opencsv to read only data from header caste1?


Solution

  • There is no built in functionality in opencsv for reading from a column by name.

    The official FAQ example has the following example on how to read from a file:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
       // nextLine[] is an array of values from the line
       System.out.println(nextLine[0] + nextLine[1] + "etc...");
    }
    

    You simply fetch the value in second column for each row by accesing the row with nextLine[1] (remember, arrays indices are zero based).

    So, in your case you could simply read from the second line:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
       System.out.println(nextLine[1]);
    }
    

    For a more sophisticated way of determining the column index from its header, refer to the answer from Scott Conway.