ReadFile Using Java

To read a file, use below class ReadFile – it is defined in a way that one can use this as Utility class.


package com.dirtyyourhands;

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

public class ReadFile {
  public void readFileContents(String fileName) {
    BufferedReader bufferReader = null;
    try {
      String lineRead;
      bufferReader = new BufferedReader(new FileReader(fileName));
      while ((lineRead = bufferReader.readLine()) != null) {
        System.out.println(lineRead);
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      try {
        if (bufferReader != null)
          bufferReader.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    }
  }
}

The above class is defined as Utility class, Let’s test it:



package com.dirtyyourhands;

public class ReadFileTest {
  public static void main(String[] args) {
    ReadFile readFile = new ReadFile();
    readFile.readFileContents("C:/test.txt");
  }
}