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
- For maven project, you can include the OpenCSV maven dependency in pom.xml file.
<dependency><groupId>com.opencsv</groupId><artifactId>opencsv</artifactId><version>4.1</version></dependency>chevron_rightfilter_none - For Gradle Project, you can include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
- 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 :
- 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.
// Java code to illustrate reading a// CSV file line by linepublicstaticvoidreadDataLineByLine(String file){try{// Create an object of filereader// class with CSV file as a parameter.FileReader filereader =newFileReader(file);// create csvReader object passing// file reader as a parameterCSVReader csvReader =newCSVReader(filereader);String[] nextRecord;// we are going to read data line by linewhile((nextRecord = csvReader.readNext()) !=null) {for(String cell : nextRecord) {System.out.print(cell +"\t");}System.out.println();}}catch(Exception e) {e.printStackTrace();}}chevron_rightfilter_none - 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();
Code:
// Java code to illustrate reading a// all data at oncepublicstaticvoidreadAllDataAtOnce(String file){try{// Create an object of file reader// class with CSV file as a parameter.FileReader filereader =newFileReader(file);// create csvReader object and skip first LineCSVReader csvReader =newCSVReaderBuilder(filereader).withSkipLines(1).build();List<String[]> allData = csvReader.readAll();// print Datafor(String[] row : allData) {for(String cell : row) {System.out.print(cell +"\t");}System.out.println();}}catch(Exception e) {e.printStackTrace();}}chevron_rightfilter_none
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 constrctor 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();
Code:
// Java code to illustrate // Reading CSV File with different separator public static void readDataFromCustomSeperator(String file) { try { // Create an object of file reader class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom seperator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with parameter // filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // Print Data. for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } |
Example – Reading two csv Files result.csv and results_semicolon_Seperator.csv
result.csv has default separator ‘, ‘ but results_semicolon_Seperator.csv has a separator ‘;’ in place of ‘, ‘.
Codes:
// Java program to illustrate reading // two CSV files // with different seperators import java.io.FileReader; import java.util.List; import com.opencsv.*; public class ReadCSVData { private static final String CSV_FILE_PATH = "D:\\EclipseWorkSpace\\CSVOperations\\results.csv"; private static final String CSV_FILE_CUSTOM_SEPERATOR = "D:\\EclipseWorkSpace\\CSVOperations\\results_semicolon_Seperator.csv"; public static void main(String[] args) { System.out.println("Read Data Line by Line With Header \n"); readDataLineByLine(CSV_FILE_PATH); System.out.println("_______________________________________________"); System.out.println("Read All Data at Once and Hide the Header also \n"); readAllDataAtOnce(CSV_FILE_PATH); System.out.println("_______________________________________________"); System.out.println("Custom Seperator here semi-colon\n"); readDataFromCustomSeperator(CSV_FILE_CUSTOM_SEPERATOR); System.out.println("_______________________________________________"); } public static void readDataLineByLine(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // filereader as parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readAllDataAtOnce(String file) { try { // Create an object of filereader class // with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object // and skip first Line CSVReader csvReader = new CSVReaderBuilder(filereader) .withSkipLines(1) .build(); List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } public static void readDataFromCustomSeperator(String file) { try { // Create object of filereader // class with csv file as parameter. FileReader filereader = new FileReader(file); // create csvParser object with // custom seperator semi-colon CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); // create csvReader object with // parameter filereader and parser CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); // Read all data at once List<String[]> allData = csvReader.readAll(); // print Data for (String[] row : allData) { for (String cell : row) { System.out.print(cell + "\t"); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } } |
Output:
_______________________________________________ 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 Seperator 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 _______________________________________________
In future articles, we will include more Operations on CSV file using OpenCSV.
References: CSVReader class Documentation, OpenCSV Documentation
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Writing a CSV file in Java using OpenCSV
- Mapping Java Beans to CSV Using OpenCSV
- Mapping CSV to JavaBeans Using OpenCSV
- Reading and Writing data to excel file using Apache POI
- Different ways of Reading a text file in Java
- Working with csv files in Python
- Difference Between CSV and Excel
- Difference Between JSON and CSV
- Remove the Chrome's "No file chosen option" from a file input using JavaScript
- Different Ways to Copy Content From One File to Another File in Java
- Reading from a URL using URLConnection Class
- Reading selected webpage content using Python Web Scraping
- Reading and Generating QR codes in Python using QRtools
- Reading Data From Microsoft-Excel using Automation Anywhere
- Copying file using FileStreams in Java
- File handling in Java using FileWriter and FileReader
- Delete a file using Java
- Moving a file from one directory to another using Java
- How to play an Audio file using Java
- Counting number of lines, words, characters and paragraphs in a text file using Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Arijeet Bhakat

