How to read CSV file in java / Various ways to read a CSV file in java

What is a CSV file

CSV stands for Comma Separated Values. Thus each line of CSV file contains words that are separated with a comma (,). A CSV file is different from a normal text file in a manner that a normal text file has a space as a separator while a CSV file has a comma as a separator. A CSV file is stored with a .csv extension.

Reading and parsing a csv file involves reading its contents line by line and processing each line. Processing might mean using its contents to do a task or just printing it to the console. Since a csv file is a normal text file, it can be read in the same way as a text file is read in java.

In all the methods given ahead, we will be considering a sample csv file with following contents :

1,Antiseptic, Dr. Joseph Lister,England
2,Ballpoint Pen,John J. Loud,USA
3,Cement,Joseph Aspdin,England
4,Electric Battery,Volta,Italy
5,Electromagnet,William Sturgeon,England
6,Microphone,Alexander Graham Bell,USA
7,Oxygen,Antoine Laurent Lavoisier,France
8,Ozone, Christian Schonbein,Germany
9,Phosphorus,Hennig Brand,Germany

Method 1 : Using split function

Read the csv file line by line using readLine() method of java.io.BufferedReader class. Split each line on comma character to get the words of the line into an array. Now you can easily print the contents of the array by iterating over it or by using appropriate index.

static void processBySplit() {
	BufferedReader reader = null;
	try {
		reader = new BufferedReader(new FileReader("d:\\discoveries.csv"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			String[] words = line.split(",");
			System.out.println("[Discovery = \"" + words[0] + "\", Discoverer = \"" + words[1]
                        + "\", Country = \"" + words[2] + "\"]");
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”] [Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”] [Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”] [Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”] [Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”] [Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”] [Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”] [Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”] [Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

Method 2 : Using Regular Expression

This method is similar to the above method as it also utilizes split() method of java.lang.String class to extract words from the line. But in place of directly splitting over a comma, a regular expression is used. The regular expression used is “\\s*,\\s*”. This expression can be divided into 3 parts : “\\s*”, “,” and “\\s*”. The expression “\s*” matches zero or more spaces while a “,” matches a comma which means that the complete expression matches a comma with zero or more spaces on its both sides.

Thus split method in the below code splits a String on the basis of a comma which may or may not have space around it and returns an array of words in a line which are separated by comma.

static void processByRegEx() {
   BufferedReader reader = null;
   try {
	reader = new BufferedReader(new FileReader("d:\\discoveries.csv"));
	String line = null;
	while ((line = reader.readLine()) != null) {
	   String[] words = line.split("\\s*,\\s*");
	   System.out.println("[Discovery = \"" + words[0] + "\", Discoverer = \"" + words[1]
           + "\", Country = \"" + words[2] + "\"]");
	}
   } catch (FileNotFoundException e) {
	e.printStackTrace();
   } catch (IOException e) {
	e.printStackTrace();
   } finally {
	if (reader != null) {
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
      }
   }
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”] [Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”] [Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”] [Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”] [Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”] [Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”] [Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”] [Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”] [Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

Method 3 : Using OpenCSV Library

Open csv is an open source library which can be used to read a CSV file. Its main reader class is com.opencsv.Reader. This class has a readAll method which returns a list of String array. Each element of this list is a String array and represents a line of the file. Thus every element of the list is an array of the words of a line of file. If you want to read a file into an array list, then this method is the choice.

import com.opencsv.CSVReader;
import java.io.IOException;
 
static void processByOpenCsv() {
    CSVReader reader = null;
    try {
	reader = new CSVReader(new FileReader("d:\\discoveries.csv"));
	List<String[]> lines = reader.readAll();
	for (int i = 0; i < lines.size(); i++) {
		String[] lineContents = lines.get(i);
		System.out.println("[Discovery = \"" + lineContents[0] + "\", Discoverer = \"" + lineContents[1]
                + "\", Country = \"" + lineContents[2] + "\"]");
	}
    } catch (FileNotFoundException e) {
	e.printStackTrace();
    } catch (IOException e) {
	e.printStackTrace();
    } finally {
	if (reader != null) {
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
   }
}

Output

[Discovery = “1”, Discoverer = “Antiseptic”, Country = ” Dr. Joseph Lister”] [Discovery = “2”, Discoverer = “Ballpoint Pen”, Country = “John J. Loud”] [Discovery = “3”, Discoverer = “Cement”, Country = “Joseph Aspdin”] [Discovery = “4”, Discoverer = “Electric Battery”, Country = “Volta”] [Discovery = “5”, Discoverer = “Electromagnet”, Country = “William Sturgeon”] [Discovery = “6”, Discoverer = “Microphone”, Country = “Alexander Graham Bell”] [Discovery = “7”, Discoverer = “Oxygen”, Country = “Antoine Laurent Lavoisier”] [Discovery = “8”, Discoverer = “Ozone”, Country = ” Christian Schonbein”] [Discovery = “9”, Discoverer = “Phosphorus”, Country = “Hennig Brand”]

 

There is another way of reading a CSV file using com.opencsv.Reader class. This class has an iterator() method which returns an iterator over the lines of the file. Thus using iterator’s  hasNext() and next() method, a CSV file can be easily read. Type of iterator is a String array and this its next method also returns a String array which contains the words of a line.

Thus to read a file, iterate over the lines of the file 

CSVReader reader = null;
try {
   reader = new CSVReader(new FileReader("d:\\discoveries.csv"));
   Iterator<String[]> iterator = reader.iterator();
   while(iterator.hasNext()){
	String[] lineContents = iterator.next();
	System.out.println("[Discovery = \"" + lineContents[0] + "\", Discoverer = \"" + lineContents[1] 
        + "\", Country = \"" + lineContents[2] + "\"]");
   }
} catch (FileNotFoundException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
} finally {
   if (reader != null) {
	try {
		reader.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
   }
}

Open csv library can be downloaded from the below link :

If you use Maven as a build tool then following dependency needs to be added in the build file:

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>3.8</version>
</dependency>

 

Hope this post had some interesting and useful content. For any suggestions, feedback and off course appreciation, do not hesitate to comment below.

0

2
Leave a Reply

Mark Your Impression

  Subscribe  
newest oldest most voted
Notify of
Vijay
Guest
Vijay

It was indeed useful. Thanks for quality content

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.