Created
October 2, 2021 16:55
-
-
Save rahulrathore44/134c2a765fd40775ecb4e11f51f1eff3 to your computer and use it in GitHub Desktop.
Reading the Data from CSV file using apache.commons.csv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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