How to read file line by line in java program , example and code

How to read file line by line in java

By Yashwant Chavan, Views 1112, Date 02-Jun-2012

This program demonstrates to read file line by line. readLine() Method is used to read line which is associated with BufferedReader object, have a complete look

tags java java-io

ReadFileLineByLine.java

The following example show how to use the java io library to read a text file line by line. new BufferedReader(); BufferReader used to read the file InputStreamReader and br.readLine() read line till end of of the file which is indicated by null. When it reach to end of the file loop get quit.

package com.technicalkeeda.app;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFileLineByLine {
    public static void main(String[] args) {
        try {
            FileInputStream fstream = new FileInputStream("datafile.txt");

            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader( in ));
            String strLine = "";

            while ((strLine = br.readLine()) != null) {
                System.out.println(strLine);
            }

            in .close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("FileNotFoundException Exception...");
        } catch (IOException e) {
            System.out.println("IOException Exception...");
        }

    }
}

Output File Contents

One
Two
Three
....
....
....

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]