Why use CSV files?
[wp_ad_camp_5]
Sometimes we process data in bulk by reading them from files with specific format like CSV. This article demonstrates how to parse a CSV file using Apache Commons CSV. A CSV is a file format wherein values are comma-separated. Thus, CSV or comma-separated values.
Sample CSV file to read
To keep things really simple, we’ll use a small CSV file with 4 headers and 4 rows. The first row contains the header name for each column.
View CSV file using LibreOffice Calc
[wp_ad_camp_3]
Here is the content of our CSV file using LibreOffice Calc
View CSV file using text editor
Here is the content of our CSV file using any text editor. In this case, we used gedit.
The Codes
The following codes is from a class with only this method. Since we have headers, we need to use .withHeader() on CSVFormat.EXCEL to use the parse(Reader) method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public List<StudentDTO> parseCsv(String fileName) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(fileName).getFile()); List<StudentDTO> studentList = new ArrayList<>(); Reader in = new FileReader(file); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in); for (CSVRecord record : records) { StudentDTO dto = new StudentDTO(); dto.setStudentId(Integer.parseInt(record.get("STUDENT_ID"))); dto.setFirstName(record.get("FIRST_NAME")); dto.setLastName(record.get("LAST_NAME")); dto.setMiddleName(record.get("MIDDLE_NAME")); studentList.add(dto); } return studentList; } |
Download the Codes
https://github.com/Turreta/java-apache-commons-csv-example
We are using JUnit 4.12, commons-csv 1.2, and Java 8. Please see pom.xml.
Convert String to a Reader object
For simpler tests, you may want to avoid using actual CSV files. Instead, a String containing the CSV data can be converted to a Reader object and passed to the parse(Reader) method.
1 2 | Reader reader = new StringReader("STUDENT_ID,FIRST_NAME,LAST_NAME,MIDDLE_NAME\n1,A_FN,A_LN,A_MN\n"); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(reader); |
[wp_ad_camp_1]