import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class ParseCSV {
public static void main(String[] args) throws IOException {
String csvFile = "data1.csv";
String keyword = "fn";
ParseCSV firstname = new ParseCSV();
System.out.println(firstname.ParseCSV(csvFile, keyword));
}
List<String> ParseCSV (String csvFile, String keyword) throws IOException {
FileReader csvfileReader = new FileReader(csvFile);
CSVReader csvReader = new CSVReader(csvfileReader);
FileReader lineReader = new FileReader(csvFile);
LineNumberReader lineNumberReader = new LineNumberReader(lineReader);
List<String> cValue = new ArrayList<String>();
try{
// which column?
String[] nextLine;
csvReader.readNext();
int columnNum;
// find 1st line?
String firstLine = null;
while (lineNumberReader.getLineNumber() == 0){
firstLine = lineNumberReader.readLine();
}
ArrayList<String> list = new ArrayList<String>(Arrays.asList(firstLine.split("\\,")));
columnNum = list.indexOf(keyword);
while ((nextLine = csvReader.readNext()) != null) {
cValue.add(nextLine[columnNum]);
}
} finally{
csvReader.close();
csvfileReader.close();
lineReader.close();
lineNumberReader.close();
}
return cValue;
}
}
=============
sample CSV file:
id,fn,ln,nation,age
1,Lokesh,Gupta,India,32
2,David,Miller,England,34
output:
[Lokesh, David]
No comments:
Post a Comment