Reading a Text File in Java

Java has an extensive API for file handling. The following code illustrates how Java File API can be used to read text files. This example shows line by line reading of the file content. This example also assumes that a text file with the name input.txt is present in the C:\ drive. If you are using a Linux system, replace the path with something like \home\tom\input.txt.


public class FileReaderDemo {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("c:\\input.txt");
            BufferedReader reader = new BufferedReader(fr);
            String line;
            while((line=reader.readLine())!=null) {
        }catch(IOException ex) {

The above example reads lines from c:\input.txt file and outputs the lines on the console. Note the following important points illustrated by this file reading program in Java,

  • File operations can throw checked IOException. Hence you need to explicitly handle them.
  • When you use forward slash in path names, you need to escape its special meaning using an additional forward slash.
  • The class FileReader enables character by character reading of text files. However it has no facilities for reading lines.
  • Java uses decorator pattern extensively in File API. In this example we use the BufferedReader decorator class over FileReader. The BufferedReader internally buffers the reading of characters and is also aware of line breaks. Even when a single character is read, BufferedReader internally reads a block of characters from the file system. Hence whenever you request the next character, it is served from the internal buffer not from file system. This makes BufferedReader very efficient compared to FileReader.
  • The readLine() method returns null if BufferedReader encounters end of the file stream.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply