Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Read File Line by Line

Problem : How you can read line by line from a text file?

Solution :
java.io.BufferedReader class has a readLine() method which stored data from java.io.FileReader class read() method and read file line by line. Below is sample program.

Program :

Step 1 - Coding

Create a text file c:/sunilos/ReadLine.java  and copy below contents.

import java.io.BufferedReader;
import java.io.FileReader;

 * A program to read file line by line.
public class ReadLine {

    public static void main(String[] args) throws Exception{
                //FileReader reads streams of characters
        FileReader reader = new FileReader("c:/sunilos/sunilos.txt");
                //BufferedRead read text from a character-input stream.
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line = bufferedReader.readLine();
            line = bufferedReader.readLine();


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy ReadLine.java  into 'c:\sunilos' folder.
  3. It is assumed that your hard drive has c:/sunilos/sunilos.txt file.
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile ReadLine.java with help of 
    • javac ReadLine.java command.  Command will create ReadLine.class file in the same folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java ReadLine command.


A software services and corporate training company specializing in Distributed
Object Oriented and Client Server Technologies with a strong background of J2EE.


What is BufferedReader?

  • BufferedReader read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Most Interesting methods in BufferedReader?

  • close() - Close the stream.
  • mark() - Mark the present position in the stream.
  • markSupported() - Tell whether this stream supports the mark() operation, which it does.
  • read() - Read a single character.
  • readLine() - Read a line of text.
  • ready() - Tell whether this stream is ready to be read.
  • skip(long) - Skip characters

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 10:35 PM