Sitemap
2 min readOct 3, 2024

--

BufferedReader & InputStreamReader in Java

InputStreamReader 

:- Converts byte streams (like input from the keyboard) into character stream.

Class:-

java.io.InputStreamReader
BufferedReader

:- wraps around inputStreamReader to provide efficient reading of characters, arrays, or lines.

class :-

java.io.BufferedReader

Example :-

Getting a line of text from the user and printing it back.

necessary classes :-

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

Step 1 :-

Create an InputStreamReader object to read from a standard input (System.in)

System.in

is the standard input i.e. keyboard input. It is a raw byte stream.

InputStreamReader 

converts the bytes from (System.in) into characters.

InputStreamReader isr = 
new InputStreamReader(System.in);

Now, inputstreamreader is ready and waiting to convert the System.in byte (actually still raw byte) into character stream.

Get Mm Aathik’s stories in your inbox

Join Medium for free to get updates from this writer.

But we need

readLine() 

method to get user input. And that method is in (BufferedReader) class.

Step 2 :-

wrap the isr in a BufferedReader to read lines of text efficiently.

BufferedReader

reads the characters efficiently from the (InputStreamReader) and allows using methods like

readLine()
BufferedReader br = new BufferedReader(isr);

Byte stream → character stream

conversion happens when

String input = br.readLine();

Think of InputStreamReader and BufferedReader as a funnel:

When you set them up, you're just connecting the pipes (InputStreamReader and BufferedReader) to System.in.

Nothing flows through the pipes yet.

When readLine() is called, it’s like opening the valve, and then the conversion and flow happen.

Whole code :-

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


public class InputExample {
public static void main(String[] a){
try{
InputStreamReader isr =
new InputStreamReader(System.in);

BufferedReader br =
new BufferedReader(isr);

System.out.print("enter input: ");
String input = br.readLine();

System.out.print("your input: "
+ input);

br.close();
}catch(IOException e){
System.out.prinln("error: "+ e);
}
}
}

By :- Aathik _ MM

--

--