How to read from particular header in opencsv?

前端 未结 5 2872

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,12245         


        
5条回答
  •  名媛妹妹
    2021-02-20 17:58

    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.

提交回复
热议问题