This programs shows you how to read big file line by line in java?
Learn how to write a program in java for reading big text file line by line
In this tutorial I will explain you how you can read big file line by line without using large memory. With the help of the program discussed here you will be able to read big size such as 5GB, 10GB or more. Many times you may have to read the big file in your java program. For example you have to process some legacy data and add it to your new database system.
Example discussed here is very useful in reading big file line by line in Java.
In this tutorial we will use java.io.BufferedReader and java.io.FileReaderwith classes of java.io package. These two classed will help us in making java program which reads the big file line by line.
About java.io.BufferedReader class
This class is used to read character files easily in Java program. Constructor takes file name as parameter.
About java.io.BufferedReader class
This class is used to efficiently read characters, arrays, and lines from input stream. Its constructor takes input stream as input. Important methods of java.io.BufferedReader class is:
read() - It reads a character from the input stream.
read(char[] cbuf, int off, int len) - This method reads characters into a portion of an array.
readLine() - This method is used to read a complete line. It returns string line.
Following is complete example of java program that reads big text file line by line and then prints on console.
import java.io.*; /** This example code reads the big txt file libne by line */ public class ReadBigFileLineByLine { public static void main(String[] args) { try{ //Big file to read String fileName = "MyBigFile.txt"; //Create FileReader object FileReader fileReader = new FileReader(fileName); //Instantiate BufferReader class BufferedReader bufferedReader = new BufferedReader(fileReader); String oneLine; //Read file line by line while ((oneLine = bufferedReader.readLine()) != null) { //Prints the content on console System.out.println(oneLine); //Write your own code here for processing the data } //Close the buffer reader bufferedReader.close(); }catch(Exception e){ System.out.println("Error while reading file:" + e.getMessage()); } } }