Reading Data from a CSV file

Reading data from a CSV File:

Before Starting to Understand how to read data from a CSV file let us understand the basics of how to read data from a file.

The classes that we need are BufferedReader and FileReader class:

https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

https://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html


1. FileReader Class:

The file reader class is used to read a file as a stream of chars.

The FileReader Class extends the Reader Class.

If you want to read a file as a stream of bytes you can use InputStream but reading as stream of bytes is very slow. 

File reader reads data from a file as a stream of characters, i.e one character at a time which can be of any byte size

The Java BufferedReader class, java.io.BufferedReader, provides buffering for your Java Reader instances. Buffering can speed up IO quite a bit.

Rather than read one character at a time from the underlying Reader, the Java BufferedReader reads a larger block (array) at a time. This is typically much faster, especially for disk access and larger data amounts.

The Java BufferedReader is similar to the BufferedInputStream but they are not exactly the same. The main difference between BufferedReader and BufferedInputStream is that BufferedReader reads characters (text), whereas the BufferedInputStream reads raw bytes.

String readLine(): The readLine() method in BufferedReader class reads one line at a time from the underlying file reader. i.e. it returns the entire line as a String.

Reading data from file:

public class Test{

     File file = new File("C:\\Users\\Krunal.Kadu\\Desktop\\Krunal\\Dump\\TestFile.txt");

     FileReader fr = new FileReader(); //reads file as a stream of characters

     BufferedReader br  = new BufferedReader();

     String line = br.readline(); //will read first line from the buffer

     while(line!=null){   

                        System.out.println(line);

                        line = br.readline(); //will read next line from the buffer. This will return null if there is                                                             //no line left to read from the file.

            }  

}

-----------------------------------------------

Code to read data from CSV file:

public class ReadCSVFile {

public static void main(String[] args) throws IOException {

File file = new File("C:\\Users\\Krunal.Kadu\\Desktop\\Krunal\\Dump\\TestFile.txt");

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

String line = br.readLine();

while(line!=null) {

String[] s = line.split(",");

for(int i=0;i<s.length; i++) {

System.out.println(s[i]);

}

line=br.readLine();

}

br.close();

}

}


Comments

Popular posts from this blog

Jenkins CICD in One Page

Why do we need a build tool?

Deutsche Bank Interview Questions - 2024