FileReader

The FileReader class creates a Reader that you can use to read the contents of a file for characters. Its two most commonly used constructors are shown here:

FileReader(String filePath)
filePath is the full path name of a file
FileReader(File fileObj)
fileObj is a File object that describes the file.

Methods inherited from class java.io.InputStreamReader

void close()
Closes the stream and releases any system resources associated with it.
String getEncoding()
Returns the name of the character encoding being used by this stream.
int read()
Reads a single character. The character read, or -1 if the end of the stream has been reached
int read(char[] cbuf, int offset, int length)
Reads characters into a portion of an array. The character read, or -1 if the end of the stream has been reached
boolean ready()
Tells whether this stream is ready to be read.

Methods inherited from class java.io.Reader

void mark(int readAheadLimit)
Marks the present position in the stream.
boolean markSupported()
Tells whether this stream supports the mark() operation.
void reset()
Resets the stream.
long skip(long n)
Skips characters.

Revised from Open JDK source code


import java.io.FileReader;

public class Main {
  public static void main(String[] argv) throws Exception {
    FileReader fr = new FileReader("text.txt");

    int ch;
    do {
      ch = fr.read();
      if (ch != -1)
        System.out.println((char) ch);
    } while (ch != -1);
    fr.close();
  }
}

The following code creates a FileReader from a filePath String

 
import java.io.FileReader;

public class MainClass {

  public static void main(String args[]) {
    try {
      int counts[] = new int[10];
      FileReader fr = new FileReader(args[0]);

      int i;
      while ((i = fr.read()) != -1) {
        char c = (char) i;
        int k = c - '0';
        if (k >= 0 && k < 10)
          ++counts[k];
      }

      // Display digit counts
      for (int j = 0; j < 10; j++) {
        char c = (char) ('0' + j);
        System.out.print(c + "=");
        System.out.print(counts[j] + "; ");
      }

      fr.close();
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}
  
Home 
  Java Book 
    File Stream  

FileReader:
  1. FileReader
  2. FileReader: read()
  3. FileReader: read(char[] cbuf)