Read CSV in Java (2024)
In this tutorial, we will demonstrate how to read CSV File in Java.
What is a CSV file?
Ans:
CSV- A comma-separated values. A CSV file contains tabular data (numbers and text) in plain-text form.
What is the difference between BufferedReader and FileReader in Java?
Ans:
A FileReader object is passed as an input to a BufferedReader object, which has all of the necessary information about the text/csv file to be read.
BufferedReader br = new BufferedReader( new FileReader("sample.csv") );
When the BufferedReader object is given the "read" instruction, it utilises the FileReader object to read data from the file. When an input is provided, the FileReader object reads 2 (or 4) bytes at a time and returns the data to the BufferedReader, and the reader continues in this manner until it encounters the characters '\n' or '\r\n' (The end of the line symbol). The reader patiently waits until the order to buffer the next line is delivered after a line has been buffered.
//read each line of the file and buffer it
while((line = br.readLine()) != null)
Meanwhile, the BufferReader object allocates a specific memory location (on RAM) named "Buffer" in which it keeps all of the data obtained from the FileReader object.
Take a look at our Suggested Posts :
Java Code to Read the CSV File
import java.io.*;
public class CSVReaderExample {
public static final String delimiter = ",";
public static void readCSVFile(String csvFile) {
try {
File file = new File(csvFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
//line variable will points to the buffered line
String line = "";
String[] lineArrStr;
//read each line of the file and buffer it
while((line = br.readLine()) != null) {
//split the line by delimiter
lineArrStr = line.split(delimiter);
for(String lineStr : lineArrStr) {
System.out.print(lineStr + " ");
}
System.out.println();
}
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
// path of csv file
String csvFile = "C:/TechGeekNext/sample.csv";
readCSVFile(csvFile);
}
}