CSV stands for Comma Seperated Values, it is the popular format used for import and exporting of data. Java by default doesn’t provide a parser for CSV hence at the end we will end up writing up a parser. OpenCSV is a third party library which can effecitively handle a CSV file. In this article we will learn how to read a CSV file and how to write data to a CSV file using OpenCSV.
OpenCSV Dependency
We will be requiring the below jars to be put in the class path for performing the Read/Write operations
- opencsv-3.6.jar
- commons-lang3-3.4.jar
Employee.csv
Lets assume we are reading the Employee.csv file which has the contents like below
EmployeeID,FirstName,LastName,Salary 1,FirstName1,LastName1,10000 2,FirstName2,LastName2,20000 3,FirstName3,LastName3,30000 4,FirstName4,LastName4,40000 5,FirstName5,LastName5,50000
Reading a CSV File using OpenCSV
OpenCSV is a Third party library, it gives better handling to parse a CSV file, we will be using CSVReader class to read the CSV File
package com.javainterviewpoint; import java.io.FileReader; import java.util.Arrays; import com.opencsv.CSVReader; public class ReadCSV_OpenCSV { public static void main(String args[]) { CSVReader csvReader = null; try { /** * Reading the CSV File * Delimiter is comma * Start reading from line 1 */ csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1); //employeeDetails stores the values current line String[] employeeDetails = null; while((employeeDetails = csvReader.readNext())!=null) { //Printing to the console System.out.println(Arrays.toString(employeeDetails)); } } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the reader csvReader.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
[1, FirstName1, LastName1, 10000] [2, FirstName2, LastName2, 20000] [3, FirstName3, LastName3, 30000] [4, FirstName4, LastName4, 40000] [5, FirstName5, LastName5, 50000]
In the above example we have read the file line by line, we can use the readAll() method, to read all the rows in a single shot. This method returns a List object back, once read we can iterate over the list like below.
readAll() Method
package com.javainterviewpoint; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.opencsv.CSVReader; public class ReadCSV_OpenCSV { public static void main(String args[]) { CSVReader csvReader = null; try { /** * Reading the CSV File * Delimiter is comma * Start reading from line 1 */ csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1); //employeeDetails stores the values current line String[] employeeDetails = null; //List for holding all the rows List<String[]> rows = new ArrayList<String[]>(); rows = csvReader.readAll(); //Read individual row from List of rows for(String[] row : rows) { System.out.println(Arrays.toString(row)); } } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the reader csvReader.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Writing data to a new CSV File
Here we will be using CSVWriter class to export the data into CSV format.
package com.javainterviewpoint; import java.io.FileWriter; import com.opencsv.CSVWriter; public class WriteCSV_OpenCSV { public static void main(String args[]) { CSVWriter csvWriter = null; try { //Create CSVWriter for writing to Employee.csv csvWriter = new CSVWriter(new FileWriter("Employee.csv")); //row1 String[] row = new String[]{"6","FirstName6","LastName6","60000"}; csvWriter.writeNext(row); //row2 row = new String[]{"7","FirstName7","LastName7","70000"}; csvWriter.writeNext(row); } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the writer csvWriter.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
When we open the Employee.csv file we can find the below content written on to it
"6","FirstName6","LastName6","60000" "7","FirstName7","LastName7","70000"
Appending to the existing CSV File
The above method will be creating a new CSV file everytime, but many times what we want is to append to the exisiting content. This can be done by passing a boolean argument to the FileWriter instance. If true contents will be appended. If false contents will be replaced.
package com.javainterviewpoint; import java.io.FileWriter; import com.opencsv.CSVWriter; public class WriteCSV_OpenCSV { public static void main(String args[]) { CSVWriter csvWriter = null; try { //Create CSVWriter for writing to Employee.csv csvWriter = new CSVWriter(new FileWriter("Employee.csv",true)); //row1 String[] row = new String[]{"6","FirstName6","LastName6","60000"}; csvWriter.writeNext(row); //row2 row = new String[]{"7","FirstName7","LastName7","70000"}; csvWriter.writeNext(row); } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the writer csvWriter.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
Now when you open the Employee.csv we will have our content appended to the existing
"6","FirstName6","LastName6","60000" "7","FirstName7","LastName7","70000" "8","FirstName8","LastName8","80000" "9","FirstName9","LastName9","90000"
Usage of writeAll() Method
In the above examples we wrote line by line only, suppose if you want to write huge data in a single shot then we can use the writeAll() method for it.
package com.javainterviewpoint; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import com.opencsv.CSVWriter; public class WriteCSV_OpenCSV { public static void main(String args[]) { CSVWriter csvWriter = null; try { //Create CSVWriter for writing to Employee.csv csvWriter = new CSVWriter(new FileWriter("Employee.csv",true)); //List of rows to be written List<String[]> rows = new ArrayList<String[]>(); rows.add(new String[]{"10","FirstName10","LastName10","100000"}); rows.add(new String[]{"11","FirstName11","LastName11","110000"}); rows.add(new String[]{"12","FirstName12","LastName12","120000"}); rows.add(new String[]{"13","FirstName13","LastName13","130000"}); //Writing list of rows to the csv file csvWriter.writeAll(rows); } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the writer csvWriter.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
In theEmployee.csv list of rows will be appended
"6","FirstName6","LastName6","60000" "7","FirstName7","LastName7","70000" "8","FirstName8","LastName8","80000" "9","FirstName9","LastName9","90000" "10","FirstName10","LastName10","100000" "11","FirstName11","LastName11","110000" "12","FirstName12","LastName12","120000" "13","FirstName13","LastName13","130000"
Leave a Reply