Latest web development tutorials

Java FileReader class

FileReader class inherits from InputStreamReader class. This class reads the data stream by character. You can create objects needed through the following constructor.

Creates a new FileReader, given the File to read from.

FileReader(File file)

Creates a new FileReader, given the data read from the FileDescriptor.

FileReader(FileDescriptor fd) 

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

FileReader(String fileName) 

After creating FIleReader objects, it can refer to the following list of file operation method.

No. File Description
1 public int read () throws IOException
Read a single character, return to the character read an int variable represents
2 public int read (char [] c , int offset, int len)
C reads characters into an array, returns the number of characters to read

Examples

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 above examples compiled results are as follows:

This
is
an
example