How to read from particular header in opencsv?

前端 未结 5 2729

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:50

    From the opencsv docs:

    Starting with version 4.2, there’s another handy way of reading CSV files that doesn’t even require creating special classes. If your CSV file has headers, you can just initialize a CSVReaderHeaderAware and start reading the values out as a map:

      reader = new CSVReaderHeaderAware(new FileReader("yourfile.csv"));
      record = reader.readMap();
    

    .readMap() will return a single record. You need to call .readMap() repeatedly to get all the records until you get null when it runs to the end (or to the first empty line), e.g.:

    Map values;
    
    while ((values = reader.readMap()) != null) {
    
        // consume the values here
    
    }
    

    The class also has another constructor which allows more customization, e.g.:

    CSVReaderHeaderAware reader = new CSVReaderHeaderAware(
            new InputStreamReader(inputStream),
            0,      // skipLines
            parser, // custom parser
            false,  // keep end of lines
            true,   // verify reader
            0,      // multiline limit
            null    // null for default locale
    );
    

    One downside which I have found is that since the reader is lazy it does not offer a record count, therefore, if you need to know the total number (for example to display correct progress information), then you'll need to use another reader just for counting lines.

    You also have available the CSVReaderHeaderAwareBuilder

提交回复
热议问题