Share on Google+Share on Google+

Java Read File Line by Line - Java Tutorial

In the tutorial I will explain you how to read a text file in Java line by line using the DataInputStream class of the Java API. The DataInputStream class used along with the BufferedReader for reading the file line by line. There are many benefits of reading the file line by line. If you read the file line by line then there will be less requirement of the memory.

Java Read File Line by Line - Example code of reading the text file in Java one line at a time


In the section of Java Tutorial you will learn how to write java program to read file line by line. We will use the DataInputStream class to Read text File Line by Line. Our example program is reading a text file (textfile.txt) one line at a time using the FileInputStream, DataInputStream and BufferedReader classes. This example of reading file is efficient and can be used to read large text files also.

Since this program is using the BufferedReader class to read the data from stream line by line, application is using very less memory and processing power. This program is effective in reading the huge text files which can range into many GB's in size.

Developers can also add the further processing logic to process the data line bye line. For example if there is requirement to process the large legacy data store in txt file then this program can be used very effectively.

You can also view the detailed tutorial of reading file line by line in Java programming language. This video tutorial will show you how you can write code, compile and then test the program.

Here is the video tutorial that explains you how to read a text file in Java one line at a time:

Video Tutorial of Java Read File Line By Line

Here is the simple Java code example which yet powerful that reads big text file one line at a time. In the following example code we have used the BufferedReader class which contains a method readLine() for reading one line of data one by one. You can easily run the example code on console or in IDE such Eclipse.

Here is the code of java program to Read text File Line by Line:

class FileRead 
 public static void main(String args[])

  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;

  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  //Close the input stream
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());

Download the code

If you run the above code, it will read "textfile.txt" file and will print the content of file on console one line at a time. Here you can add your code to process one line of data in each iteration. Such example is useful if you have to read big csv file and process the content of csv file line by line.


The Java I/O Package Examples is also very help full for anyone looking for file management examples in Java. Read the complete description of example program discussed above.

Here is the complete explanation of the program:

In this example code following Java classes and Interfaces are used:

Class DataInputStream

The DataInputStream is convenient class for reading the primitive data from the input stream. The data read by DataInputStream  is independent of the OS and machine. It can read the data from any input stream. The DataInputStream class can also read the data from output stream written by any other program. In our example discussed we are just reading the text file one line at a time. The DataInputStream  class must be used carefully as it not thread safe. Programmer must write own code for making the read thread safe in a multi threaded environment.

Implementing Data input streams and data output strings basically represents Unicode strings in such a format that can be regarded as a slight modification of UTF-8. UTF-8 or UCS Transformation Format-8-bit is a variable-width encoding which encodes each Unicode character in a set of 1 to 4 octets in which the number of octets is dependent upon the integer value assigned to the Unicode character. At present, UTF-8 is one of the major and dominant character encoding for the World Wide Web, which accounts for over half of all Web pages.

Important methods of DataInputStream class are:

  • read(byte[] b)
  • read(byte[] b, int off, int len)
  • readFully(byte[] b)
  • readDouble()

Constructor of DataInputStream class

Here are the constructor of DataInputStream class.

DataInputStream(InputStream in) - In this Constructor DataInputStream takes InputStream as constructor argument.

The BufferedReader class

The BufferedReader class is used to read data from the character input stream every efficiently. It can read data efficiently as characters, arrays and even lines. This class is very useful in reading the file line be line in Java very easily. You just have to create the object of BufferedReader class  by passing the the DataInputStream as constructor parameter and then use the methods of BufferedReader class  to read the desired data as characters, array or lines.

The BufferedReader class uses the default buffer size  of 8192 chars for reading the data into buffer. This buffer size is sufficient for general applications. But it is also possible to specify the buffer size as per requirement.

Here are the constructor of  BufferedReader  class:

BufferedReader(Reader in) - This constructor is using the default buffer size.

BufferedReader(Reader in, int sz) - Here second argument takes the buffer size as parameter.

If you don't use the BufferedReader class for reading the data line by line then the performance of the application will be very low. Because each request to the Reader internally sends the read request for underlying character or byte stream which is resource hungry and time consuming. So, developers should use the BufferedReader class to read the character stream.

Here is the example of using BufferedReader class:

 BufferedReader in
   = new BufferedReader(new FileReader("myfile.txt"));

If you don't use the buffering then the application performance will be slow. Since each time you calls the read() or readLine() method, the data will be read from the the file itself and convert into the characters. So to read the file line by line in Java you should always use the BufferedReader class.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.



Posted on: June 4, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Java Read File Line by Line - Java Tutorial   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 11, 2013
Another Way to New a BufferedReader

Instead of new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(new File(fileName))))); The following is more clear: new BufferedReader(new FileReader(filename));
Peter Lawrey
July 20, 2013
Can you not use DataInputStream to read text

DataInputStream is for reading binary not text. This bad example gets copied many, many times so can you remove DataInputStream here.
August 30, 2013
Good example of file reading

Hi, Thanks for posting such a nice tutorial. I was searching for the posts for reading a file which is very big in size, one line at a time. I also tried to read the complete file in memory but due to Java memory constraint it is not possible. So, I searched for the "Read file line by line in Java" on google and luckily found this tutorial. This post on reading file helped me a lot for solving my problem. After using the program here I am able to read big text file of around 3.5 GB without any error or memory issue. Program performance is also good. Thanks for such a nice post.
Gulam Haqqani
January 12, 2014

write a program in java that reads a text file which contains integer numbers separated by commas. Find the sum of even no's and sum of odd no's of each line. the output should be like this Line1: sume of even no's =--- & sum of odd no's = ---
Erick Sanvicente
February 16, 2014

hello, where should i put the file.txt so the program can read it?
May 8, 2014

Hi, In my project i read excel file this functionality working on my local host but i upload this project that time this functionality not working . what changes required please suggest me regards, Hitendra
tanveer islam
June 24, 2011
java file

how to create file
May 31, 2013

Hey it will read the data whatever u entered ok.But It didn't interact with File.So I am thinking it is not corrrect>Please forgive if there is wrong in my discussion
May 31, 2013

Sorry sorry I got thanq