InputStreamReader
是 Java 中用于将字节流转换为字符流的桥梁类。它继承自 Reader
类,提供了读取字节流并解码成字符的功能。
InputStreamReader
类的构造函数接受两个参数:
InputStream
对象:要进行转换的字节流。Charset
对象或字符串:用于指定字符编码方式,默认使用平台默认的字符编码方式。
下面是使用 InputStreamReader
的示例代码:
import java.io.*;
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
// 创建字节输入流
InputStream inputStream = new FileInputStream("input.txt");
// 创建 InputStreamReader 对象,并指定字符编码为 UTF-8
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int data;
// 读取字符数据
while ((data = reader.read()) != -1) {
char ch = (char) data;
System.out.print(ch);
}
// 关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上述示例中,我们首先创建一个字节输入流 inputStream
,然后使用 InputStreamReader
将其转换为字符流 reader
,并指定字符编码为 UTF-8。接下来,在一个循环中使用 reader.read()
方法逐个读取字符数据,并在控制台打印输出。
在最后,我们关闭了 reader
流。
需要注意的是,InputStreamReader
是一个字符流,用于处理文本数据。当涉及到二进制数据(如图片、视频等)时,使用字节流而不是字符流更为合适。