目录

FileReader类(FileReader Class)

此类继承自InputStreamReader类。 FileReader用于读取字符流。

该类有几个构造函数来创建所需的对象。 以下是FileReader类提供的构造函数列表。

Sr.No. 构造函数和描述
1

FileReader(File file)

给定要读取的文件,此构造函数创建一个新的FileReader。

2

FileReader(FileDescriptor fd)

在给出要读取的FileDescriptor的情况下,此构造函数创建一个新的FileReader。

3

FileReader(String fileName)

在给定要读取的文件的名称的情况下,此构造函数创建一个新的FileReader。

一旦掌握了FileReader对象,就会有一个辅助方法列表,可用于操作文件。

Sr.No. 方法和描述
1

public int read() throws IOException

读一个字符。 返回一个int,表示读取的字符。

2

public int read(char [] c, int offset, int len)

将字符读入数组。 返回读取的字符数。

例子 (Example)

以下是演示课程的示例 -

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();
   }
}

这将产生以下结果 -

输出 (Output)

This
is
an
example
↑回到顶部↑
WIKI教程 @2018