Share on Google+Share on Google+

Java Read CSV file

In this tutorial, you will learn how to read csv file.

Java Read CSV file

In this tutorial, you will learn how to read csv file.

CSV (Comma Separated Value) is a common type of data file which can be exported by many applications, spreadsheets like Excel. It is easy to read and there is no need of using any API to read these files. In the given example, we have opened a file data.csv  and created a BufferedReader object to read the data from this file in a line at a time. Then we have used StringTokenizer class to break the line using ",". The delimiter for a CSV file is a comma therefore we have used comma to break a line using StringTokenizer. The method hasMoreTokens() check for the next string and nextToken() method stores the row data into the array where each token is represented as each cell value.

Here is a csv file:


import java.util.*;

public class ReadCSV{
public static void main(String args[]){
int row = 0;
int col = 0;
String[][] numbers=new String[24][24];

File file = new File("c:/data.csv");
System.out.println("File Exists");
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;

while((line = bufRdr.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens()){
numbers[row][col] = st.nextToken();

catch (FileNotFoundException e)
catch(Exception e)
System.out.println("The following error accurred"+e);




File Exists
1       Roxi    Delhi   [email protected]
2       Mandy   Mumbai  [email protected]
3       Rixi    Agra    [email protected]
4       Jenson  Chennai [email protected]
5       Andrew  Kolkata [email protected]


Posted on: September 26, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.