How to read and parse CSV file

This tutorial shows how to read, parse and print out the values from a CSV file. Say we have a CSV file user-profile.csv where the user name, roll number, age, course name is stored, seperated by comma.

Sample file data

“Aman”,”A1234″,23,”B.Tech”
“Rahul”,”A1235″,21,”B.Tech”
“Ravi”,”A1236″,24,”B.Tech”
“Maxwell”,”A1237″,23,”B.Tech”
“Patrick”,”A1238″,26,”B.Tech”
“John”,”A1239″,20,”B.Tech”

Extracts the Roll Number and Course from above CVS file, and print it out.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadUserProfileCVS {
 
  public static void main(String[] args) {
 
	ReadUserProfileCVS obj = new ReadUserProfileCVS();
	obj.getProfile();
 
  }
 
  public void getProfile() {
 
	String csvFile = "user-profile.csv";
	BufferedReader br = null;
	String line = "";
 
	try {
 
		br = new BufferedReader(new FileReader(csvFile));
		while ((line = br.readLine()) != null) {
		        // use comma as separator
			String[] userProfile = line.split(",");
 
			System.out.println("User Profile [Roll No.= " + userProfile[1] 
                                 + " , name=" + userProfile[3] + "]");
 
		}
 
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (br != null) {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
  }
 
}