FileReader

In this chapter you will learn:

  1. What is Java FileReader and how to use FileReader
  2. How to read value into a character array

Use 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.

The following code reads a text file character by character.

import java.io.FileReader;
//  j  a v a  2s .  c  o  m
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();
  }
}

Read into a character array

char[] read(char[] cbuf) read characters from the FileReader and save to cbuf array

import java.io.FileReader;
/*from   j a  va2s.  co  m*/
public class Main {
  public static void main(String[] argv) throws Exception {
    FileReader fr = new FileReader("text.txt");
    int count;
    char chrs[] = new char[80];

    do {
      count = fr.read(chrs);
      for (int i = 0; i < count; i++)
        System.out.print(chrs[i]);
    } while (count != -1);

  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is Java BufferedReader and how to use BufferedReader
  2. Create BufferedReader from System.in
  3. How to use BufferedReader to read a text file line by line