Java FileReader class


The FileReader class inherits from the InputStreamReader class. This class reads data from the stream character by character. The required objects can be created through the following construction methods.

Creates a new FileReader given a File to read data from.

FileReader(File file)

Creates a new FileReader given a FileDescriptor to read data from.

FileReader(FileDescriptor fd)

Creates a new FileReader given the name of a file to read data from.

FileReader(String fileName)

After successfully creating the FIleReader object, you can refer to the methods in the following list to operate the file.

Serial numberFile description
1public int read( ) throws IOException
Read a single character and return an int variable representing the read character
2public int read (char [] c, int offset, int len)
Read characters into the c array and return the number of characters read

Example

import java.io.*;public class FileRead{
   public static void main(String args[])throws IOException{  File file = new File("Hello1.txt");  // 创建文件  file.createNewFile();  // creates a FileWriter Object  FileWriter writer = new FileWriter(file); 
      // 向文件写入内容  writer.write("This\n is\n an\n example\n"); 
      writer.flush();  writer.close();  // 创建 FileReader 对象  FileReader fr = new FileReader(file); 
      char [] a = new char[50];  fr.read(a); // 读取数组中的内容  for(char c : a)  System.out.print(c); // 一个一个打印字符  fr.close();
   }}

The compilation and running results of the above example are as follows:

Thisisan
example