Home Tutorial Java Core Java Read CSV file


Share on Google+Share on Google+
Java Read CSV file
Posted on: September 26, 2012 at 12:00 AM
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.io.*;
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   roxi@roseindia.net
2       Mandy   Mumbai  mandy@roseindia.net
3       Rixi    Agra    rixi@roseindia.net
4       Jenson  Chennai jenson@roseindia.net
5       Andrew  Kolkata andrew@roseindia.net

Related Tags for Java Read CSV file:

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.

Posted on: September 26, 2012

Recommend the tutorial

Advertisements Advertisements