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

We can use Reader such as FileReader for reading a text file in Java. FileReader is a convenience class meant for reading streams of characters from files that work only with the default character encoding.

 
To read the contents of a text file, the idea is to create a new FileReader and read the whole file character by character using Reader’s read() method, as shown below. It returns the character read, or -1 if the end of the stream is reached, and throws an IOException if an I/O error occurs.

Download Code

 
The read() method has an overloaded version that can read a specified length of the characters from the input stream into an array of chars. We can use this method to read the whole file into a character array at once. The contents of the character array are then copied into a new string using the String constructor, as shown below:

Download Code

 
In case the file is too large to read in a single read operation, we can use another overloaded version of the read() method, which can repeatedly read the specified number of chars into a buffer until the end of the file has been reached. This is demonstrated below:

Download Code

 
Using FileReader is a very inefficient way of reading a text file in Java. To improve the performance in huge files, it is recommended to use a BufferedReader on top of a FileReader. This is demonstrated below:

Download Code

 
In Java 8 and above, we can use the BufferedReader.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 text file using FileReader in Java.

 
Read More:

Read all text from a file into a String in Java