This post will discuss how to read the contents of a file using BufferedReader in Java.

The BufferedReader class in Java reads text from a character-input stream, buffering characters so as to provide for the efficient read. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. Therefore, it is advisable to wrap a BufferedReader around any Reader whose read operations may be costly, such as FileReaders and InputStreamReaders.

1. BufferedReader’s readLine() method

BufferedReader’s readLine() method reads a line of text. Each invocation of the readLine() method would read bytes from the file, convert them into characters, and then return. This is demonstrated below using a FileReader for reading a text file:

Download Code

 
FileReader is meant for reading streams of characters. Another solution is to use the BufferedReader with InputStreamReader.

The following code reads streams of raw bytes using FileInputStream and decodes them into characters using a specified charset using an InputStreamReader, and form a string using a platform-dependent line separator.

Download Code

2. BufferedReader’s lines() method

In Java 8 and above, we can use the BufferedReader’s lines() method to get a stream of lines of text read from BufferedReader. This is demonstrated below:

Download Code

That’s all about reading a file using BufferedReader in Java.

 
Read More:

Read all text from a file into a String in Java