Signup/Sign In

Java BufferedReader

The BufferedReader class is part of the java.io package and extends the Reader class. BufferedReader is used to read text from a character input stream and buffers the characters for better performance.

In this tutorial, we will learn more about this class.

What is BufferedReader?

  • As discussed above, BufferedReader is a class used to read text from some source(like files or sockets).
  • BufferedReader wraps another reader or input stream to increase the overall efficiency and performance of our program.
  • A BufferedReader uses a buffer to store the data read from the source. It decreases the number of I/O operations required.
  • Several readers like FileReader and InputStreamReader have costly read operations, and it is better to wrap them using BufferedReader.

BufferedReader Constructor

The BufferedReader class provides two constructors. Each of them takes a Reader as a parameter. We can also specify the size of the underlying buffer in the constructor. The default buffer size is 8KB.

BufferedReader?(Reader in)
BufferedReader?(Reader in, int bufferSize)

BufferedReader with Another Reader

Let's wrap a FileReader with the BufferedReader. We can use it to read data from a file.

String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader by wrapping the FileReader

In the later sections, we will use it to read data from the files in different ways.

BufferedReader with a Stream

We can create a BufferedReader using an input stream as a source.

Let's wrap the InputStreamReader and read data from System.in. It will read data that we enter using the keyboard. The code below demonstrates this.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader bufferedReader = new BufferedReader(isr);//Creating a BufferedReader		
		System.out.println("Enter Something");
		String line = bufferedReader.readLine();
		System.out.print("You Entered: " + line);		
		bufferedReader.close();//Closing the stream
	}
}

The image below shows the output.

Code Output

Closing the Stream

We should always use the close() method of the BufferedReader to release all the system resources associated with the reader. We don't need to explicitly call this method if we are using a try-with-resources block.

BufferedReader VS Scanner

Both Scanner and BufferedReader can read data from an external source. However, there are some differences between the two.

  • BufferedReader class is synchronized and thread-safe, whereas the Scanner class is not synchronized.
  • The Scanner class has a smaller buffer of fixed size(1KB). BufferedReader can change the size of the buffer. Also, the default size of the buffer used by BufferedReader is much more than the Scanner class.
  • BufferedReader is faster than Scanner as it reads data without parsing it.
  • A Scanner will hide the IOException. With a BufferedReader, we need to handle this exception.

Reading Files Line by Line

The BufferedReader class provides several methods to read data. The readLine() method reads one line at a time. This method returns null if we reach the end of the stream. Let's read a file using this method. The demo.txt file contains the following lines.

This is a Demo File.
We will read this file using BufferedReader.
This is the end of file.

The code to read the file is shown below.

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

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
		FileReader fileReader = new FileReader(path);
		BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader
		
        String line;
		int lineCount = 0;
		//Reading the file line by line
		while( (line = bufferedReader.readLine()) != null ) 
		{
			lineCount += 1;
			System.out.println("Line: " + lineCount);
			System.out.println(line + "\n");
		}		
        bufferedReader.close();//Closing the stream
	}
}


Line: 1
This is a Demo File.

Line: 2
We will read this file using BufferedReader.

Line: 3
This is the end of file.

Reading Single Characters from a File

We can also read a single character at a time by using the read() method of the BufferedReader class. This method returns the char read as an integer. If we reach the end of the stream, then it returns -1. The code below demonstrates this method's working. Our file contains the text "Hello World!".

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

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
		FileReader fileReader = new FileReader(path);
		BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader
		
		int charRead;
		//Reading the file one char at a time
		while( (charRead = bufferedReader.read()) != -1 ) 
		{
			System.out.println((char)charRead);
		}		
		bufferedReader.close();//Closing the stream
	}
}


H
e
l
l
o

W
o
r
l
d
!

Reading Multiple Characters from a File

The read() method can also read multiple characters at once. We need to pass a char array in which it will store the data. We also need to use an offset that indicates the starting index of the char array. The stored data starts from this index. We also need to mention the maximum length of characters to read.

Our file contains the text "HelloWorld". We want to read "Hello" from the file. The code below demonstrates how to do this.

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

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
		FileReader fileReader = new FileReader(path);
		BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader
		
		char[] charArr = new char[5];
		bufferedReader.read(charArr, 0, 5);//reading 5 characters into the charArr
		System.out.print(charArr);		
		bufferedReader.close();//Closing the stream
	}
}


Hello

Skipping Characters

The BufferedReader class provides a skip() method, which we can use to skip characters. It takes a long type parameter. Suppose our file contains the text "H*e*l*l*o". After reading each character, we need to skip one character as we don't want to read the asterisks.

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

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
		FileReader fileReader = new FileReader(path);
		BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader
		
		int charRead;
		StringBuilder sb = new StringBuilder();
		//Reading the file one char at a time
		while( (charRead = bufferedReader.read()) != -1 ) 
		{
			sb.append((char)charRead);
			bufferedReader.skip(1L);//Skipping one character
		}		
		System.out.print(sb);
		bufferedReader.close();//Closing the stream
	}
}


Hello

Mark and Reset

The BufferedReader class provides us the mark() method to mark a specific character. We can come back to this marked character anytime in the future by using the reset() method. The mak() method takes an integer as input that denotes the maximum bytes that can be read before the mark becomes invalid.

Suppose our file contains the text "He*llo". We will read all the characters but mark the asterisk. Then we will come back to this mark using reset().

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

public class Demo
{	
	public static void main(String[] args) throws IOException
	{
		String path = "C:\\Users\\Lenovo\\Desktop\\Demo.txt";
		FileReader fileReader = new FileReader(path);
		BufferedReader bufferedReader = new BufferedReader(fileReader);//Creating a BufferedReader
		
		char[] charArr = new char[5];
		
		charArr[0] = (char)bufferedReader.read();//H
		charArr[1] = (char)bufferedReader.read();//e
		
		bufferedReader.mark(10);//Marked the asterisk
		bufferedReader.skip(1);//Skipped the asterisk
		
		charArr[2] = (char)bufferedReader.read();//l
		charArr[3] = (char)bufferedReader.read();//l
		charArr[4] = (char)bufferedReader.read();//o
		System.out.println(charArr);
		
		bufferedReader.reset();//Going back to the mark
		char asterisk = (char) bufferedReader.read();//Reading the asterisk
		System.out.print(asterisk);
		
		bufferedReader.close();//Closing the stream
	}
}


Hello
*

Summary

The BufferedReader class reads data from a source like a file or a stream. It improves the performance of other readers by using a buffer that reduces the number of I/O operations. The BufferedReader class provides several convenient methods to read data. We can use the readLine() method to read individual lines. The read() method can read single or multiple characters.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.