How to read file line by line in java

 Posted On  | Yashwant Chavan 

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

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
....
....
....


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0225 seconds.