Java FileReader 类
Java FileReader 类
在本教程中,我们将通过示例了解 Java FileReader 及其方法。
FileReader
java.io
的类 包可用于从文件中读取数据(以字符为单位)。
它扩展了 InputSreamReader
类。
在了解 FileReader
之前 ,请确保您了解 Java 文件。
创建文件读取器
为了创建文件阅读器,我们必须导入 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
在上面的例子中,我们创建了 2 个名为 input1 的文件阅读器 和 input2 .
- 输入1 没有指定字符编码。因此
getEncoding()
方法返回默认的字符编码。 - 输入2 指定字符编码,UTF8 .因此
getEncoding()
方法返回指定的字符编码。
注意 :我们使用了 Charset.forName()
方法来指定字符编码的类型。要了解更多信息,请访问 Java Charset(官方 Java 文档)。
close() 方法
要关闭文件阅读器,我们可以使用 close()
方法。一旦 close()
方法被调用,我们不能使用阅读器读取数据。
FileReader的其他方法
方法 | 说明 |
---|---|
ready() | 检查文件阅读器是否准备好阅读 |
mark() | 在文件阅读器中标记已读取数据的位置 |
reset() | 将控件返回到阅读器中设置标记的位置 |
要了解更多信息,请访问 Java FileReader(Java 官方文档)。
java