Reading data from CSV files
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:
Reading data from CSV files in column format(Similar to GBM Project)
1. First we get the column names in line string variable. (br.readline() method of BufferedReader class is used to read next line from the Buffer).
2. Then we use line.split() which splits the line into tokes and returns an array. The string is divided into tokens based on the delimiter provided.
3. Then we take another String variable line2 and assign the next line from the buffer to this variable.This line is futher splitted and each individual token is added to the Hashmap with the keys.
Comments
Post a Comment