Java InputStreamReader 类详细介绍以及用法详解
在本教程中,我们将通过示例了解 Java InputStreamReader 类以及相关用法。
在本教程中,我们将通过示例了解 Java InputStreamReader 类以及相关用法。
java.io
包的 InputStreamReader
类用于将输入流中的字节数据转换为字符数据。
InputStreamReader
类扩展了 Reader
抽象类。
InputStreamReader
类要处理的是其他的输入流对象将输入流中的字节读取为字符,因此它也被称为字节流和字符流之间的桥梁。
创建 InputStreamReader
我们使用 InputStreamReader
的构造方法创建对象,需要通过构造方法的参数指定要关联的输入流对象。如下:
// 文件输入流
FileInputStream file = new FileInputStream(String path);
// InputStreamReader 与文件输入流关联起来
InputStreamReader input = new InputStreamReader(file);
在上面的例子中,我们先创建了一个文件输入流对象,并将文件输入流对象作为参数传递到 InputStreamReader
构造方法中。
在这里, InputStreamReader
使用系统默认编码读取文件中的数据。当系统默认编码与文件编码不一致,就会出现乱码,这时就需要我们传入字符编码,比如 UTF8
或 UTF16
等。 如下所示:
InputStreamReader input = new InputStreamReader(file, Charset cs);
在这里,我们使用了 Charset
类来指定文件中的字符编码。
InputStreamReader 的方法
InputStreamReader
类完全实现了 Reader
类定义的所有抽象方法。
read() 方法
ready()
- 检查Reader
流是否准备好被读取read(char[] array)
- 从流中读取字符并存储在指定的数组中read(char[] array, int start, int length)
- 读取长度为length
字符并存储在指定数组start
开始的位置中
假设我们有一个文件 input.txt
内容如下:
This is a line of text inside the file.
我们使用 InputStreamReader
读取文件内容。
import java.io.InputStreamReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
char[] array = new char[100];
try {
FileInputStream file = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(file);
input.read(array);
System.out.println("Data in the stream: ");
System.out.println(array);
input.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
输出
Data in the stream: This is a line of text inside the file.
在上面的例子中,我们使用文件输入流创建了一个 InputStreamReader
对象,并与文件 input.txt
关联起来。如下:
FileInputStream file = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(file);
然后我们使用了 read()
方法从文件中读取字符。
getEncoding() 方法
getEncoding()
方法获取用于输入流用来存储数据的编码名称。例如,
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("input.txt");
InputStreamReader input1 = new InputStreamReader(file);
InputStreamReader input2 = new InputStreamReader(file, StandardCharsets.ISO_8859_1);
System.out.println("Character encoding of input1: " + input1.getEncoding());
System.out.println("Character encoding of input2: " + input2.getEncoding());
input1.close();
input2.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
输出
Character encoding of input1: UTF8
Character encoding of input2: ISO_8859_1
在上面的例子中,我们创建了 2 个 InputStreamReader
对象:
input1
不指定字符编码。因此,getEncoding()
方法返回系统默认字符编码名称。input2
指定字符编码ISO_8859_1
。因此,getEncoding()
方法返回指定的字符编码。
close() 方法
我们可以使用 close()
方法关闭 Reader
对象。一旦 close()
方法被调用,我们就不能读取数据了。
InputStreamReader 的其他方法
方法 | 描述 |
---|---|
ready() |
检查流是否准备好被读取 |
mark() |
标记流中已读取数据的位置 |
reset() |
将控制返回到流中设置标记的点 |