Reading Text based Files in Java

You are currently viewing Reading Text based Files in Java

The Java IO package provides FileReader class to read contents of a text based file such as txt, html or XML. The most common method to read text file in java is to call read method of FileReader class in the loop and continuously check the return byte of the read method. Read method returns -1 when it reaches at the end of the file and there are no contents to read. However, you must need to keep in mind that read method throws FileNotFoundException if the file you are trying to read does not exist. It also throws IOException if there is any other IO related error during the file reading process.

Following code example demonstrates how you should read text file contents with all types of exception handling routines. 

import java.io.*;

public class FileReaderTest
{
      public static void main(String[] args) 
      {
            FileReader r = null;
            StringBuffer contents = new StringBuffer();
            try
            {
                  String path = "C:\\myfile.txt"; 
                  r = new FileReader(path);  
                  int i; 
   
                  while(  ( i = r.read() ) != -1 )
                  {
                        contents.append( (char) i);
                  }
                  System.out.println(contents);
            }
            catch(FileNotFoundException ex)
            {
                  System.out.println("File Not Found");
            }
            catch(IOException ex)
            {
                  System.out.println("File I/O Error");
            }
            finally
            {
                   try
                   {
                        if(r != null)
                              r.close();
                  }
                  catch(IOException ex)
                  {
                        System.out.println("File I/O Error");
                  }
            }
      }
}
READ ALSO:  Singleton Design Pattern in Java

Leave a Reply