Reputation: 4360
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.in(Standard input stream)-
gets the input from keyboard in bytes
InputStreamReader:
Converts the bytes into Unicode characters/ converts the standard input into reader object to be used with BufferedReader
Finally BufferedReader
: Used to read from character input stream(Input stream reader)
String c = br.ReadLine();
-- a method used to read characters from input stream and put them in the string in one go not byte by byte.
Is everything above right ? Please correct if anything wrong !
Upvotes: 1
Views: 6494
Reputation:
Bufferedreader is a java class, the following is the hierarchy of this class.
java.lang.Object ==> java.io.Reader ==> java.io.BufferedReader
Also, BufferedReader provides an efficient way to read content. Very Simple.. Let's have a look at the following example to understand.
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
BufferedReader contentReader = null;
int total = 0; // variable total hold the number that we will add
//Create instance of class BufferedReader
//FileReader is built in class that takes care of the details of reading content from a file
//BufferedReader is something that adds some buffering on top of that to make reading fom a file more efficient.
try{
contentReader = new BufferedReader(new FileReader("c:\\Numbers.txt"));
String line = null;
while((line = contentReader.readLine()) != null)
total += Integer.valueOf(line);
System.out.println("Total: " + total);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally{
try{
if(contentReader != null)
contentReader.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
Upvotes: 0
Reputation: 1503439
Nearly there, but this:
String c = br.readLine();
-- a method used to read characters from input stream and put them in the string in one go not byte by byte.
It reads characters from the input reader (BufferedReader
doesn't know about streams) and returns a whole line in one go, not character by character. Think of it in layers, and "above" the InputStreamReader
layer, the concept of "bytes" doesn't exist any more.
Also, note that you can read blocks of characters with a Reader
without reading a line: read(char[], int, int)
- the point of readLine()
is that it will do the line ending detection for you.
(As noted in comments, it's also readLine
, not ReadLine
:)
Upvotes: 6