BufferedReader
is a class in Java that simplifies reading text from a character input stream. It buffers the characters in order to enable efficient reading of text data. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
BufferedReader
extends the abstract class Reader
and maintains an internal buffer of 8192 characters. During the read operation in BufferedReader
, a chunk of characters is read from the disk and stored in the internal buffer. And from the internal buffer, characters are read individually. Hence, the number of communication to the disk is reduced. This is why reading characters is faster using BufferedReader
.
BufferedReader
is useful when we want to read text from any kind of input source, whether that be files, sockets, or something else. It enables us to minimize the number of I/O operations by reading chunks of characters and storing them in an internal buffer. While the buffer has data, the reader will read from it instead of directly from the underlying stream.
Some key methods of BufferedReader
include:
close()
: Closes the stream and releases any system resources associated with it.lines()
: Returns aStream
of lines extracted from thisBufferedReader
.mark()
: Marks the present position in the stream. Subsequent calls toreset()
will attempt to reposition the stream to this point.read()
: Reads a single character.readLine()
: Reads a line of text.reset()
: Resets the stream to the most recent mark.skip(long n)
: Skips characters.
It is advisable to wrap a BufferedReader
around any Reader
whose read()
operations may be costly, such as FileReaders
and InputStreamReaders
.