To read a text file, we use FileReader and wrap it in a BufferedReader.

In the below example, we read a file named “FileToRead.txt” which is located in my local system and output the file line by line in my eclipse console.

Sample Program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package classOneGeneral;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadFromFile {
public static void main(String [] args) throws IOException {
/*FileReader is meant for reading streams of characters.
For reading streams of raw bytes, consider using a FileInputStream.*/
    FileReader fileReader = new FileReader(“D:\\FileToRead.txt”);
    /*BufferedReader reads text from a character-input stream, buffering characters
    so as to provide for the efficient reading of characters, arrays, and lines. */
    BufferedReader bufferReader = new BufferedReader(fileReader);
 
    String textfromfile = null; //
    // Using while loop to read the file until there are no more lines
    while( (textfromfile = bufferReader.readLine()) != null ){
        System.out.println(textfromfile);
    }
    fileReader.close();
    // Close the BufferedReader object to prevent memory leak
    bufferReader.close();
}
}

Read More: Java Tutorial