Java FileReader类
该类继承自InputStreamReader类。FileReader用于读取字符流。
该类有多个构造函数来创建所需的对象。下面是FileReader类提供的构造函数列表。
| 序号 | 构造函数及描述 | 
|---|---|
| 1 | FileReader(File file) 这个构造函数根据给定的文件创建一个新的FileReader对象。 | 
| 2 | FileReader(FileDescriptor fd) 这个构造函数根据给定的FileDescriptor创建一个新的FileReader对象。 | 
| 3 | FileReader(String fileName) 这个构造函数根据给定的文件名创建一个新的FileReader对象。 | 
一旦你手中有FileReader对象,那么就有一系列可用于操作文件的辅助方法。
| 序号 | 方法与描述 | |
|---|---|---|
| 1 | public int read() throws IOException 读取一个字符。返回一个int,表示读取的字符。 | |
| 2 | public int read(char [] c, int offset, int len) 将字符读入数组中。返回读取的字符数。 | 
示例
以下是一个示例,用于演示类:
import java.io.*;
public class FileRead {
   public static void main(String args[])throws IOException {
      File file = new File("Hello1.txt");
      // creates the file
      file.createNewFile();
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();
      // Creates a FileReader Object
      FileReader fr = new FileReader(file); 
      char [] a = new char[50];
      fr.read(a);   // reads the content to the array
      for(char c : a)
         System.out.print(c);   // prints the characters one by one
      fr.close();
   }
}
这将产生以下结果−
输出
This
is
an
example
极客教程