Java InputStreamReader
InputStreamReader是从字节流到字符流的桥梁: 它读取字节并使用指定的字符集将其解码为字符。它使用的字符集可以按名称指定,也可以明确指定,也可以接受平台的默认字符集。
构造函数
构造函数名称 |
说明 |
InputStreamReader(InputStream in) |
它将创建一个使用默认字符集的InputStreamReader。 |
InputStreamReader(InputStream in,Charset cs) |
它将创建一个使用给定字符集的InputStreamReader。 |
InputStreamReader(InputStream in,CharsetDecoder dec) |
它将创建一个使用给定字符集解码器的InputStreamReader。 |
InputStreamReader(InputStream in,字符串charsetName) |
它将创建一个使用命名字符集的InputStreamReader。 |
方法
修饰符和类型 |
方法 |
说明 |
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