java.io
包中的FileReader
类可用于从文件中读取数据(以字符形式)。
它继承了InputSreamReader类。

在学习FileReader
之前,请确保您了解Java File。
创建 FileReader
为了创建文件读取器,我们必须首先导入java.io.FileReader
包。导入包后,我们可以这样创建文件读取器。
1. 使用文件名
FileReader input = new FileReader(String name);
在这里,我们创建了一个文件读取器,它将链接到由name指定的文件。
2. 使用文件对象
FileReader input = new FileReader(File fileObj);
在这里,我们创建了一个文件读取器,它将链接到由文件对象指定的文件。
在上面的示例中,文件中的数据是使用一些默认的字符编码存储的。
但是,从Java 11开始,我们还可以指定文件中的字符编码类型(UTF-8 或 UTF-16)。
FileReader input = new FileReader(String file, Charset cs);
在这里,我们使用Charset
类来指定文件读取器的字符编码。
FileReader 的方法
FileReader
类提供了Reader
类中各种方法的实现。
read() 方法
read()
- 从读取器读取单个字符read(char[] array)
- 从读取器读取字符并将其存储在指定的数组中read(char[] array, int start, int length)
- 从读取器读取等于length的字符数,并从位置start开始将其存储在指定的数组中
例如,假设我们有一个名为input.txt的文件,内容如下。
This is a line of text inside the file.
让我们尝试使用FileReader
读取文件。
import java.io.FileReader;
class Main {
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
Data in the file: This is a line of text inside the file.
在上面的示例中,我们创建了一个名为input的文件读取器。该文件读取器链接到文件 input.txt。
FileInputStream input = new FileInputStream("input.txt");
为了从文件中读取数据,我们使用了read()
方法。
注意:文件 input.txt 应该存在于当前工作目录中。
getEncoding()方法
可以使用getEncoding()
方法获取用于在文件中存储数据的编码类型。例如,
import java.io.FileReader;
import java.nio.charset.Charset;
class Main {
public static void main(String[] args) {
try {
// Creates a FileReader with default encoding
FileReader input1 = new FileReader("input.txt");
// Creates a FileReader specifying the encoding
FileReader input2 = new FileReader("input.txt", Charset.forName("UTF8"));
// Returns the character encoding of the file reader
System.out.println("Character encoding of input1: " + input1.getEncoding());
System.out.println("Character encoding of input2: " + input2.getEncoding());
// Closes the reader
input1.close();
input2.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
The character encoding of input1: Cp1252 The character encoding of input2: UTF8
在上面的示例中,我们创建了两个名为input1和input2的文件读取器。
- input1未指定字符编码。因此,
getEncoding()
方法返回默认字符编码。 - input2指定了字符编码 UTF8。因此,
getEncoding()
方法返回指定的字符编码。
注意:我们使用了Charset.forName()
方法来指定字符编码类型。要了解更多信息,请访问Java Charset(官方Java文档)。
close() 方法
要关闭文件读取器,我们可以使用close()
方法。调用close()
方法后,我们无法再使用读取器读取数据。
FileReader 的其他方法
方法 | 描述 |
---|---|
ready() |
检查文件读取器是否已准备好读取 |
mark() |
标记文件读取器中已读取数据的为止 |
reset() |
将控件返回到读取器中设置标记的点 |
要了解更多信息,请访问Java FileReader(官方Java文档)。