How to read Text Files in Java

File Reading is quite a common need and we all need it from time to time. In this post lets see how to read Text file in Java.

Why just text files?

Text files are character oriented file and Java has different set of classes to handle character oriented and binary files. Like we shall be using java.io.Reader and subclasses in the post, whereas for binary data we need to use InputStream and its related classes.

To read a file, we need to do the following

  • Create a File instance
  • Create a Reader
  • Read lines and process the line

Let’s see the code

public void readFile(String fileName) throws IOException {
    File fileTobeRead = new File(fileName);

    BufferedReader bufferedReader = new BufferedReader(new FileReader(fileTobeRead));
    String line = null;

    while((line = bufferedReader.readLine()) != null) {
      processLine(line);
    }
  }

The code is simple. We create a file reader to read the file. Here we have used BufferedReader so that we can use the buffering to enhance performance. This is also a great example of Decorator Pattern.

We read read line and pass the line to a function which could do further processing (in this case, simply print on the console). The readLine() API would return null, once all the lines have been read.

Everything Together

Let’s see everything together

package com.codezuzu.algo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * codezuzu.com
 */
public class TextFileReading {

  public void readFile(String fileName) throws IOException {
    File fileTobeRead = new File(fileName);

    BufferedReader bufferedReader = new BufferedReader(new FileReader(fileTobeRead));
    String line = null;

    while((line = bufferedReader.readLine()) != null) {
      processLine(line);
    }
  }

  private void processLine(String line) {
    System.out.println(line);
  }

  public static void main(String[] args) throws IOException {
    TextFileReading textFileReading = new TextFileReading();
    textFileReading.readFile(args[0]);
  }

}

Happy Coding !

3 thoughts on “How to read Text Files in Java

Leave a Reply

Your email address will not be published. Required fields are marked *