Java教程-Java FileReader类

Java FileReader类
Java FileReader类用于从文件中读取数据。它返回字节格式的数据,就像FileInputStream类一样。
它是面向字符的类,用于Java的文件处理。
Java FileReader类声明
让我们看一下Java.io.FileReader类的声明:
public class FileReader extends InputStreamReader
FileReader类的构造函数
Constructor | Description |
---|---|
FileReader(String file) | 它在string中获取文件名。它以读取模式打开给定的文件。如果文件不存在,它会抛出 FileNotFoundException。 |
FileReader(File file) | 它在文件实例中获取文件名。它以读取模式打开给定的文件。如果文件不存在,它会抛出 FileNotFoundException。 |
FileReader类的方法
Method | Description |
---|---|
int read() | 它用于返回 ASCII 形式的字符。它在文件末尾返回 -1。 |
void close() | 它用于关闭 FileReader 类。 |
Java FileReader示例
在此示例中,我们使用Java FileReader类从文本文件testout.txt中读取数据。
package com.javatpoint;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
假设您在"testout.txt"文件中有以下数据:
Welcome to javaTpoint.
输出:
Welcome to javaTpoint.