Java – how do I read from a specific header in opencsv?
•
Java
I have a CSV file I want to extract specific columns from it For example:
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 to use opencsv to read only the data in the header file caste1?
Solution
There is no built - in function in opencsv to read columns by name
Official FAQ example has the following examples 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 only need to access rows using nextline [1] to get the values in the second column of each row (remember, the array index is based on zero)
So, in your case, you can 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 complex method of determining the column index from its title, see the answer from Scott Conway
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码