java.io.BufferedReader

This document is intended to provide discussion and examples of the usage of BufferedReader. We will be going through the basic syntax of BufferedReader class, use of its methods and principles. Make sure to understand and master the use of this class since this is one of the most used class in java.

BufferedReader Class Declaration

public class BufferedReader extends Reader

Compatibility Version

Requires Java 1.1 and up

BufferedReader Basics

The BufferedReader class main functionality is to reads text from inputstream. Morever it is used to buffer characters for the purpose of efficient handling of characters, arrays and strings.

There are 2 constructors available for BufferedReader class but for the purpose of simplicity we will concentrate on the basic constructor which takes a Reader as method argument. Lets take a look on below example on how to instantiate a BufferedReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

You would have noticed that we have initialized the BufferedReader object br by calling one of its constructors that takes Reader object as a method argument. Reader class alone is not sufficient so we have to take one of its subclass the InputStreamReader to read InputStream.  On this BufferedReader example, we have used the System.in which corresponds to keyboard input or another input source specified by the host environment or user.

BufferedReader Example to Get the User Input

Below is a full concrete example of BufferedReader class taking a user input from the console.

package com.javatutorialhq.java.examples;

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

/*
 * A BufferedReader example that reads user input from the console
 */

public class BufferedReaderExample {

	public static void main(String[] args) {

		// instantiate BufferedReader object
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("Input your name:");

		// initialize our Buffer
		StringBuffer sb = new StringBuffer("Welcome ");

		// read the user input
		try {
			sb.append(br.readLine());
			
			// closing our BufferedReader object
			br.close();

			// Printing a welcome message
			System.out.println(sb);
		} catch (IOException e) {
			System.out.println("Error Encountered getting user input:"
					+ e.getMessage());
			e.printStackTrace();
		}

	}

}

So what is the purpose of the above example. Basically we just get the user input from the console and then print a welcome message. Lets dig in on each part of the code.

First we have initialized our BufferedReader as what we have explained earlier using the constructor that takes Reader as method argument. After we have initialized our BufferedReader we have printed using System.out.print the message “Input your name: ” which basically just asking the user to input his name on the console using keyboard as instrument. After which we have initialize a StringBuffer object with Initial contents of “Welcome “. Please go through on our StringBuffer examples to know more on this. Our intention in declaring the StringBuffer “sb” is to prepare our welcome message that is Welcome YourName.

Now that we have already declared all the things we need, we now read the user input using the method of BufferedReader class readline(). This method returns a complete line of String representation of what has been inputted by the user on the console. We then append the result of readLine method to our StringBuffer using the append method. After getting what we need from the user input on the console we have invoked the close() method in order to close the stream. Dont’t forget to call the close method to avoid memory leak and further complications on your code.

You might have noticed that we have also enclosed our code with try-catch block. This is because the readLine and close() method throws IOException thus we either have to catch this or to throw it back. In any case that we encounter an IOException this java program will output a sensible message and the full stacktrace of what has happened.

Java BufferedReader Example to Read a File

On this example we would be dealing a more complicated example of using BufferedReader. On the earlier example we have used InputStreamReader as our constructor argument. On this example we would using FileReader. The intention is to read the contents of a file and output it to the console. Though I prefer using the Scanner to read file, using BufferedReader had some benefits. Lets take a look on below example:

package com.javatutorialhq.java.examples;

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

/*
 * A BufferedReader example that reads a file line by line
 */

public class BufferedReaderExample {

	public static void main(String[] args) {

		try {
			// instantiate BufferedReader object
			BufferedReader br = new BufferedReader(new FileReader(new File(
					"C:/temp/countries.txt")));
			String line = "";
			while((line=br.readLine())!=null){
				System.out.println(line);
			}
			br.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not exists or insufficient rights");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("An exception occured while reading the file");
			e.printStackTrace();
		}

	}

}

If we run the above java code we will be having the following console output

BufferedReader Read File Output

BufferedReader Read File Output

From the above code you might have noticed that we have passed a FileReader to the BufferedReader constructor. The FileReader constructor takes a File as an argument thus we have initialized a new File “C:/temp/countries.txt”. Don’t get confused by the way we are invoking the constructor. To make it simple below is the equivalent of BufferedReader br = new BufferedReader(new FileReader(new File(“C:/temp/countries.txt”)));

			File f = new File("C:/temp/countries.txt");
			FileReader fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);

We only want to make the code more simpler by chaining the objects rather than initializing it one by one using variables. The choice of whichever is better is under the decision of the programmer. Whatever method suits you best, would be the better solutions. Going back to the discussion after we have initialized our BufferedReader object, we have loop through each line of the file by calling the br.next line together with the while loop. The while loop idea is that until the readLine() does not return null, we will iterate through each line while printing what has been read. Pretty easy isn’t it. You might not have believed that I have started using this same strategy in reading a file using BufferedReader way back in 2005. That’s 10 years have passed and yet this solution still works fine.

Since the FileReader requires FileNotFoundException to be handled, we have surround the code block with try-catch. If a FileNotFoundException were encountered, a meaningful message to the console will be shown with the intention of telling the user that the source file doesn’t exists or insufficient permission. Now that we have tackled mos of the handling of BufferedReader, lets now go through the list of methods available.

BufferedReader Class Methods

The following are the list of methods available. The method name is clickable and you will be redirected to specific method example.

Modifier and Type Method and Description
void close() – Closes the stream and releases any system resources associated with it.
Stream<String> lines() – Returns a Stream, the elements of which are lines read from this BufferedReader.
void mark(int readAheadLimit) – Marks the present position in the stream.
boolean markSupported() – Tells whether this stream supports the mark() operation, which it does.
int read() – Reads a single character.
int read(char[] cbuf, int off, int len) – Reads characters into a portion of an array.
String readLine() – Reads a line of text.
boolean ready() – Tells whether this stream is ready to be read.
void reset() – Resets the stream to the most recent mark.
long skip(long n) – Skips characters.