Java教程-Java InputStreamReader(输入流读取器)

Java InputStreamReader(输入流读取器)
InputStreamReader是从字节流到字符流的桥梁:它通过使用指定的字符集将字节读取并解码为字符。它使用的字符集可以通过名称指定,也可以显式给出,或者可以接受平台的默认字符集。
构造函数
Constructor name | Description |
---|---|
InputStreamReader(InputStream in) | 它创建一个使用默认字符集的 InputStreamReader。 |
InputStreamReader(InputStream in, Charset cs) | 它创建一个使用给定字符集的 InputStreamReader。 |
InputStreamReader(InputStream in, CharsetDecoder dec) | 它创建一个使用给定字符集解码器的 InputStreamReader。 |
InputStreamReader(InputStream in, String charsetName) | 它创建一个使用指定字符集的 InputStreamReader。 |
方法
Modifier and Type | Method | Description |
---|---|---|
void | close() | 它关闭流并释放与其关联的所有系统资源。 |
String | getEncoding() | 它返回此流使用的字符编码的名称。 |
int | read() | 它读取一个字符。 |
int | read(char[] cbuf, int offset, int length) | 它将字符读入数组的一部分。 |
boolean | ready() | 它告诉这个流是否准备好被读取。 |
示例
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
I love my country
The file.txt contains text "I love my country" the InputStreamReader
reads Character by character from the file