Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”).
OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.
How to Use OpenCSV
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
1. For maven project, you can include the OpenCSV maven dependency in pom.xml file.
2. For Gradle Project, you can include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
3. You can Download OpenCSV Jar and include in your project class path.
Some useful classes of opencsv
- CSVReader – This class provides the operations to read the CSV file as a list of String array.
- CSVWriter – This class allows us to write the data to a CSV file.
- CsvToBean – This class will be used when you want to populate your java beans from a CSV file content.
- BeanToCsv – This class helps to export data to CSV file from your java application.
Reading CSV File
For reading a CSV file you need CSVReader class. Following are sample CSV file that we’ll read.
name, rollno, department, result, cgpa amar, 42, cse, pass, 8.6 rohini, 21, ece, fail, 3.2 aman, 23, cse, pass, 8.9 rahul, 45, ee, fail, 4.6 pratik, 65, cse, pass, 7.2 raunak, 23, me, pass, 9.1 suvam, 68, me, pass, 8.2
We can read csv file by two ways :
1. Read data line by line : Lets see how to read CSV file line by line. For reading data line by line, first we have to construct and initialize CSVReader object by passing the filereader object of CSV file. After that we have to call readNext() method of CSVReader object to read data line by line as shown in below code.
2. Read all data at once : We read the CSV records one by one using the readNext() method. CSVReader also provides a method called readAll() to read all the records at once into a List.
List allData = csvReader.readAll();
When we read csv file by default, header will not ignored, as shown in output of above codes. When we need to skip the first element in the list then we can specify start line while creating CSVReader.
CSVReader csvReader = new CSVReaderBuilder(reader).withSkipLines(1).build();
Reading CSV File with different separator
CSV files can be separated with a delimiter other than a comma e.g. semi-colon, pipe etc. The following example shows how to read data of CSV file separated by a semi-colon character.
Semi-colon separated CSV file example :
name;rollno;department;result;cgpa amar;42;cse;pass;8.6 rohini;21;ece;fail;3.2 aman;23;cse;pass;8.9 rahul;45;ee;fail;4.6 pratik;65;cse;pass;7.2 raunak;23;me;pass;9.1 suvam;68;me;pass;8.2
For Custom separator first CSVParser with specific parser character is created.
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
Then we will create CSVReader object withCSVParser() method along with constructor and provided the made parser object to parameter of withCSVParser method.At last call build method to build object.
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
Example – Reading two csv Files result.csv and results_semicolon_Separator.csv
result.csv has default separator ‘, ‘ but results_semicolon_Separator.csv has a separator ‘;’ in place of ‘, ‘.
_______________________________________________ Read Data Line by Line With Header name rollno department result cgpa amar 42 cse pass 8.6 rohini 21 ece fail 3.2 aman 23 cse pass 8.9 rahul 45 ee fail 4.6 pratik 65 cse pass 7.2 raunak 23 me pass 9.1 suvam 68 me pass 8.2 _______________________________________________ Read All Data at Once and Hide the Header also amar 42 cse pass 8.6 rohini 21 ece fail 3.2 aman 23 cse pass 8.9 rahul 45 ee fail 4.6 pratik 65 cse pass 7.2 raunak 23 me pass 9.1 suvam 68 me pass 8.2 _______________________________________________ Custom Separator here semi-colon name rollno department result cgpa amar 42 cse pass 8.6 rohini 21 ece fail 3.2 aman 23 cse pass 8.9 rahul 45 ee fail 4.6 pratik 65 cse pass 7.2 raunak 23 me pass 9.1 suvam 68 me pass 8.2 _______________________________________________