How to read contents from file?

Requirement

Read contents from a text file.

Code Explanation

java.io package provides API to read and write both text and binary data streams. For dealing with binary data there are two top level abstract classes - java.io.InputStream and java.io.OutputStream. On the other hand, to deal with character data top level abstract classes are - java.io.Reader and java.io.Writer. In this case to read content from text file we choose to use java.io.FileReader, a subclass of java.io.Reader. It's a simple three step process:

  1. Create an instance of java.io.FileReader with the source file path
  2. Create a java.io.BufferedReader linking the file reader object
  3. Start reading data from buffer

The BufferedReader is used to minimize actual file access. The BufferedReader has default size 8 KB. However, it can be changed while creating the BufferedReader.

In this example we are reading contents line by line from buffer and directly printing to console.

24     /**
25      * Reads content from a file denoted by given path and prints to console.
26      * @param filePath The absolute path of the file.
27      */
28     public void read(String filePath) {
29         BufferedReader fileBuffer = null;
30         FileReader fileReader = null;
31         File file = new File(filePath);
32         try {
33             fileReader = new FileReader(file);
34             fileBuffer = new BufferedReader(fileReader);
35             String lineContent = null;
36             while ((lineContent = fileBuffer.readLine())
37                     != null) {
38                 System.out.println(lineContent);
39             }
40         } catch (FileNotFoundException ex) {
41             ex.printStackTrace(System.err);
42         } catch (IOException ex) {
43             ex.printStackTrace(System.err);
44         } finally {
45             closeIOStream(fileBuffer);
46             closeIOStream(fileReader);
47         }
48     }
49 
    

The following method is a helper method to close a given java.io.Reader resource.

54     private void closeIOStream(Reader reader) {
55         if (reader != null) {
56             try {
57                 reader.close();
58             } catch (Exception ex) {
59                 System.err.println("Failed to close input stream.");
60                 ex.printStackTrace(System.err);
61             } finally {
62                 reader = null;
63             }
64         }
65     }
66 
    

The main method of program calls read() method to read file content. The source file path can optionally be passed as command line argument. If no input argument is passed, file path is assumed in the program.

67     /**
68      * Main method to test file reading.
69      * @param args Input arguments.
70      */
71     public static void main(String[] args) {
72         String inputFile = "E:/Leisure/poems/fav.txt";
73         if (args.length > 0) {
74             inputFile = args[0];
75         }
76         new ReadFile().read(inputFile);
77     }
78 }
79 
    

Download

You may download the complete source code from here: