BufferedReader in java

In this section you will learn about BufferedReader in java with example. Java provide java.io.Reader package for reading files, this class contain BufferedReader under the package java.io.BufferedReader.

BufferedReader in java

In this section you will learn about BufferedReader in java with example. Java provide java.io.Reader package for reading files, this class contain BufferedReader under the package java.io.BufferedReader.

BufferedReader in java

BufferedReader in java

In this section you will learn about BufferedReader in java with example. Java provide java.io.Reader package for reading files, this class contain BufferedReader under the package java.io.BufferedReader. This class read text from input stream by buffering character so that it can read character, array and lines efficiently.

In general each read request made by reader causes similar read request to character or byte stream. So, it is advisable to use BufferedReader .

BufferedReader br = new BufferedReader(new FileReader("demo.txt"));

It will buffer the input from the file, without buffering, invocation of each read request could cause byte to read from file, then converting into character and then returned, which is very time consuming and space complexity will also increase.

Java provide two constructor they as follows :

BufferedReader(Reader in) :  That create a buffer for character input stream with default size.

BufferedReader(Reader in, int size) :  That create a buffering with the size specified in integer.

 Some of the method of BufferedReader are; close() to close the stream and release the space associated with it, read() that read a single character, readLine() that read a line of text, reset() to reset the stream to recent mark, mark(int readaheadlimit) to mark the current position in the stream.

Example : A code to use BufferedReader in java.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReader1 
 {
  public static void main(String args[])
  {
	  BufferedReader br=null;
	  try
	  {
	  String st;
	  br= new BufferedReader(new FileReader("C://Demo.txt"));
	    while((st = br.readLine()) != null)
	   {
	     System.out.println(st);
	    }
	  }catch(IOException e){ e.printStackTrace(); }
	  finally {
		  
          try {
              if (br!= null)
                  br.close();
          } catch (IOException ex) {
              ex.printStackTrace();
          }
	  
	  }   
    }
 }

In the above example through BufferedReader reading the file, using while loop reading each charcter until it reaches end of file, and assigning the character to the string st and the printing the string st to the console.

Output : After compiling and executing  above program.

Download SourceCode