How to read a file in Java efficiently using BufferedReader and Scanner class?

How to read a file in Java efficiently using BufferedReader and Scanner class?


Posted in : Core Java Posted on : January 17, 2014 at 6:44 PM Comments : [ 0 ]

In this tutorial you will learn how to read a text file line by line in Java using the BufferedReader and Scanner class.

How to read a file in Java using BufferedReader and Scanner class? Example program of reading text file in Java one line at a time.

In this tutorial we are providing two of the many ways of reading a file in Java, one is by using BufferedReader and the other is by using Scanner class.

Reading file using BufferedReader class

The BufferedReader class is very convenient class for reading the text file one line at at time. This class is very efficient class which can use to read the text file of any size. Following classes are used to read the text file:

  • java.io.BufferedReader
  • java.io.FileInputStream
  • java.io.InputStream
  • java.io.InputStreamReader

BufferedReader class makes the task easy and quick as it reads text from a character-input stream. By default this class uses the buffer size of 8192 chars for reading the data into buffer however you can specify the size of Buffer. It can be used to read data like characters, arrays and lines.

To read the text or character first create an object of BufferedReader class by passing the the DataInputStream as constructor parameter. And then use BufferedReader class to read the data. It consumes very less memory and processing power.

Method of BufferedReader class:

The java.io.BufferedReader.read() method is used to read a character from the input stream.

But in our example we will use the readline() method of the BufferedReader class.

The method readline() is used to read the next line.

Syntax of readline() method:

public String readLine() throws IOException;

Constructors used in BufferedReader class:

  • BufferedReader(Reader in) is used for the default buffer size
  • BufferedReader(Reader in, int sz) takes the buffer size as parameter

Following is the example of read file in Java using BufferedReader:

package net.roseindia;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderExample {
   public static void main(String[] args) throws Exception {
      
      try{
         //Open input stream for reading the text file MyTextFile.txt
         InputStream is = new FileInputStream("MyTextFile.txt");
         
         // create new input stream reader
         InputStreamReader instrm = new InputStreamReader(is);
         
         // Create the object of BufferedReader object
         BufferedReader br = new BufferedReader(instrm);
      
         String strLine;
         
         // Read one line at a time 
         while((strLine = br.readLine()) != null)
         {    
            // Print line
            System.out.println(strLine);
         }
         
      }catch(Exception e){
         e.printStackTrace();
      }
   }
}

You can also use Scanner class to read a file in Java. The java.util.Scanner class is used to parse the primitive types and strings. If you are using scanner class you no longer require to convert a string to integer as they are directly read from the file. Scanner class use delimiters to break input into tokens. By default delimiter is white space. It is recommended not to use Scanner class in multithreading.

Scanner class uses asNextLine(), nextInt(), nextLong() and nextLine() method to read the contents of a file.

hasnextLine() returns true, if a line exists or returns false if it doesn't.

nextline() returns the current line and throws a FileNotFound exception if the file doesn't exist.

Following is the example of read file in Java using Scanner Class:

package net.roseindia;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ScannerFileReadExample {

    public static void main(String args[]) throws FileNotFoundException {
  
        //Create the file object
        File fileObj = new File("MyTextFile.txt");
      
        //Scanner object for reading the file
        Scanner scnr = new Scanner(fileObj);
      
        //Reading each line of file using Scanner class
        while(scnr.hasNextLine()){
            String strLine = scnr.nextLine();
			//print data on console
            System.out.println(strLine);
        }       
    
    }   
  
}

After running the example you will get following output on the console:

D:\Tutorials\examples\devmanuals>java ScannerFileReadExample
Read file line by line in Java - Line 1
Read file line by line in Java - Line 2
Read file line by line in Java - Line 3
Read file line by line in Java - Line 4
Read file line by line in Java - Line 5
Read file line by line in Java - Line 6
Read file line by line in Java - Line 7
Read file line by line in Java - Line 8
Read file line by line in Java - Line 9
Read file line by line in Java - Line 10
Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics