Java BufferedReader

Learn to read a file or keyboard input in Java using BufferedReader. Use the given code as template and reuse it the way you like.

BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

1. Reading a file with BufferedReader

FileReader class is used for reading streams of characters from a file. For reading streams of raw bytes, consider using a FileInputStream.

Example 1: Java example to read a file line by line using BufferedReader and FileReader

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

public class BufferedReaderExample 
{
	public static void main(String[] args)
	{
		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\temp\\testOut.txt")))
		{
 
			String currLine;
 
			while ((currLine = bufferedReader.readLine()) != null) 
			{
				System.out.println(currLine);
			}
 
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}

2. Reading Console Input with BufferedReader

InputStreamReader class is used for reading the data from the underlying byte-input stream. Wrapping an InputStreamReader within a BufferedReader provides the top efficiency.

Example 2: Java program to read the user input from Console using BufferedReader and InputStreamReader

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

public class BufferedReaderExample 
{
	public static void main(String[] args)
	{
		try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)))
		{
                      System.out.println("Enter your name");    
                      String name=br.readLine();    
                      System.out.println("Welcome "+name);    
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.