I'm looping csv. I have two question:
1) I'm selecting second column by name like
if(tab[1].equals("Col2")
I don't want to put the name of column. I want to select just second column.
2) how to skip first line (header)
Here is sample of code to looping csv:
String csvFile = "C:\\test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try{
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] tab=line.split(cvsSplitBy);
int tmp;
if(tab[1].equals("Col2")){
tmp = Integer.parseInt(tab[2]);
for(int i=0;i<tmp;i++){
// TO DO
}
}
}
}
Better to make use of CSVReader
for this, which provides lot of APIs for processing your csv files. Here is a complete working code, ofcourse, without exception handling.
String csvFile = "C:\\test.csv";
CSVReader reader;
String[] nextRow;
char cvsSplitBy = ';';
try {
//Last argument will determine how many lines to skip. 1 means skip header
reader = new CSVReader(new FileReader(csvFile), cvsSplitBy, CSVParser.DEFAULT_QUOTE_CHARACTER, 1);
while ((nextRow = reader.readNext()) != null) {
if(nextRow.length > 2){
//nextRow[1] will always give second column value
int tmp = Integer.parseInt(nextRow[1]);
for (int i = 0; i < tmp; i++) {
// TO DO
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}