java files

How to read csv file in java

This tutorial shows you how to read a csv file in java with example, follows the below steps.

Required Jar File

Download Here opencsv-3.8.jar

Sample csv File sample.csv

package com.candidjava.csv;

import java.io.File;
import java.io.FileReader;
import java.util.Scanner;

import com.opencsv.CSVReader;


public class CSVRead {
public static void main(String[] args) throws Exception {
	//Using Scanner Class
	File file=new File("F:/CSVFile/sample.csv");
	Scanner sc=new Scanner(file);
	//sc.useDelimiter(",");
	while(sc.hasNext())
	{
		System.out.println(sc.next());
	}
	sc.close();
	//Using CSV Reader
	FileReader fr=new FileReader(file);
	CSVReader csvread=new CSVReader(fr);
	String[] record;
	while((record=csvread.readNext()) !=  null)
	{
		
		for(String cell:record)
		{
			System.out.println(cell);
		}
		System.out.println("\n");
	}
}
}

OutPut

Name,Designation,Age
Raj,Clerk,25
Ram,Accountant,27
Hari,Manager,35
Priya,Sr.Manager,40
Raghu,Accountant,25
Name
Designation
Age


Raj
Clerk
25


Ram
Accountant
27


Hari
Manager
35


Priya
Sr.Manager
40


Raghu
Accountant
25