Java Read CSV file


 

Java Read CSV file

In this tutorial, you will learn how to 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:

Example

import java.io.*;
import java.util.*;

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

File file = new File("c:/data.csv");
if(file.exists()){
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,",");
col=0;
while (st.hasMoreTokens()){
numbers[row][col] = st.nextToken();
System.out.print(numbers[row][col]+"\t");
col++;
}
System.out.println();
row++;
}
bufRdr.close();
}

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

}

}

Output:

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]

Ads