How to read from particular header in opencsv?

前端 未结 5 2712

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 18:03

    Magnilex and Sparky are right in that CSVReader does not support reading values by column name. But that being said there are two ways you can do this.

    Given that you have the column names and the default CSVReader reads the header you can search the first the header for the position then use that from there on out;

    private int getHeaderLocation(String[] headers, String columnName) {
       return Arrays.asList(headers).indexOf(columnName);
    }
    

    so your method would look like (leaving out a lot of error checks you will need to put in)

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    String [] nextLine;
    int columnPosition;
    
    nextLine = reader.readNext();
    columnPosition = getHeaderLocation(nextLine, "castle1");
    
    while ((nextLine = reader.readNext()) != null && columnPosition > -1) {
       // nextLine[] is an array of values from the line
       System.out.println(nextLine[columnPosition]);
    }
    

    I would only do the above if you were pressed for time and it was only one column you cared about. That is because openCSV can convert directly to an object that has the variables the same as the header column names using the CsvToBean class and the HeaderColumnNameMappingStrategy.

    So first you would define a class that has the fields (and really you only need to put in the fields you want - extras are ignored and missing ones are null or default values).

    public class CastleDTO {
       private int id1;
       private String castle1;
       private double salary;
       private String name1;
    
       // have all the getters and setters here....
    }
    

    Then your code would look like

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    HeaderColumnNameMappingStrategy castleStrategy = new HeaderColumnNameMappingStrategy();
    CsvToBean csvToBean = new CsvToBean();
    
    List castleList = csvToBean.parse(castleStrategy, reader);
    
    for (CastleDTO dto : castleList) {
       System.out.println(dto.getCastle1());
    }
    

提交回复
热议问题