Skip to content

Instantly share code, notes, and snippets.

@rahulrathore44
Created October 2, 2021 16:55
Show Gist options
  • Save rahulrathore44/134c2a765fd40775ecb4e11f51f1eff3 to your computer and use it in GitHub Desktop.
Save rahulrathore44/134c2a765fd40775ecb4e11f51f1eff3 to your computer and use it in GitHub Desktop.
Reading the Data from CSV file using apache.commons.csv
package com.automation.csvconfig;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class ReadCSVFile {
private String fileName;
public ReadCSVFile(String fileName) {
this.fileName = fileName;
}
private List<CSVRecord> getCsvData() throws IOException {
File csvFile = new File(fileName);
List<CSVRecord> recordList = new ArrayList<CSVRecord>();
FileReader reader = null;
try {
reader = new FileReader(csvFile);
CSVParser parser = CSVParser.parse(reader, CSVFormat.newFormat(','));
recordList = parser.getRecords();
// Add the call to close method
} catch (IOException e) {
// Log the exception
return Collections.emptyList();
}finally {
if(reader != null)
reader.close();
}
return recordList;
}
public String getRecordAtIndex(int rowIndex, int columnIndex) throws IOException {
List<CSVRecord> csvRecords = getCsvData();
if(rowIndex < 0 && rowIndex > csvRecords.size()) {
throw new IllegalArgumentException(String.format(" Invalid index %s ", rowIndex));
}
return csvRecords.get(rowIndex).get(columnIndex);
}
public static void main(String[] args) throws IOException {
// This is how you call the api
ReadCSVFile reader = new ReadCSVFile("C:\\Data\\log\\test.csv");
System.out.println(reader.getRecordAtIndex(0, 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment