×

Java Programs

Java Practice

Java program to read a CSV File

The files which contain values spirited by commas are known as CSV files and here, we are going to learn how to read a CSV file using java program?
Submitted by Jyoti Singh, on January 31, 2018

CSV is a Comma separated Value file where each value in the file is separated by a comma.

For example,

    "Abhishek Sharma","B.E ,"C.S.E ,"22"
    "Vikarna"," Singh","B.E","Civil","23"
    "Kajal " ,"Namdev","B.E","C.S.E","22"
    "Nikita"," Sharma","B.E","C.S.E","22"

Our CSV file that is stored at the location "H:/CSVFiles/csvfile.csv' . To read this file create a class in java eclipse and add the following code in it:

package logicProgramming;

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

public class CSVSeprator {

	public static void main(String[] args) {
	
		//this holds the Csv file location
		String csvFile = "H:/CSVFiles/csvfile.csv";
		String line = "";
		//as we have to split the file from commas
		String splitBy = ","; 
		
		//Buffered reader class is a java.io class which reads 
		//a character input file ,it reads lines and arrays 
		//File reader opens the given file in read mode 
		try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
			//readline function is use to read a line form the file
			while ((line = br.readLine()) != null) {
			//loop will continue until the line ends 
			String[] name = line.split(splitBy);
			//split function use to split the words in the line by commas
			System.out.println("FirstName: "+ name[0]+ " , LastName:" + name[1]+ " , Mobile:" + name[2]+ " , Email:" + name[3]);
			//this is to print the each csv line 
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

This code will read the CSV file and show the output like this:

Output

Using java - read CSV file



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.