Site icon NgDeveloper

how to read csv file in java example?

Title: Reading CSV File in Java Example Program

CSV is abbreviation of Comma Separated Values. CSV file is also just a plain text file along with some delimiters [familiar one is ,]. It is used to store the data with comma separation. We have an option in excel also to export the column values as csv with comma delimited to share the file.

Sample CSV File:

[plain]

Name, Profession, Place, Qualification
Naveen kumar G, Developer, Chennai, BE CSE
Sivachudar, Business Analyst, Chennai, MTech
RV Selva kumar, Business, Vellore, BE ECE
Hema kumar, Teacher, Arcot, Bsc Bed

[/plain]

Java Program to Read the CSV File:

[java]package in.javadomain;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CSVFileRead {

public static void main(String[] args) {
// CSV File location
String csvFileLoc = "D:\\csvfile.csv";
// Delimiter of CSV file
String splitBy = ",";
String[] csvContents = null;
String eachLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader(csvFileLoc));
while((eachLine=br.readLine()) !=null){
csvContents =eachLine.split(splitBy);
System.out.println("Name ==> "+csvContents[0]);
System.out.println("Profession ==> "+csvContents[1]);
System.out.println("Place ==> "+csvContents[2]);
System.out.println("Qualification ==> "+csvContents[3]);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

[/java]

Output:

[plain]
Name ==> Name
Profession ==> Profession
Place ==> Place
Qualification ==> Qualification
Name ==> Naveen kumar G
Profession ==> Developer
Place ==> Chennai
Qualification ==> BE CSE
Name ==> Sivachudar
Profession ==> Business Analyst
Place ==> Chennai
Qualification ==> MTech
Name ==> RV Selva kumar
Profession ==> Business
Place ==> Vellore
Qualification ==> BE ECE
Name ==> Hemakumar
Profession ==> Teacher
Place ==> Arcot
Qualification ==> Bsc Bed

[/plain]

 

 

Exit mobile version